2018年湖北省赛（网络赛）-E: Jump A Jump（类最短路）

#include<bits/stdc++.h>
using namespace std;
const int MAX=1e5+30;
const int MOD=1e9+7;
const double PI=acos(-1);
typedef long long ll;
struct lenka
{
ll x,c;
int operator<(const lenka& q)const{return q.c<c;}
};
priority_queue<lenka>p;
int v[5001],a[2010],n;
ll d[5001];
void solve()
{
while(!p.empty())
{
lenka now=p.top();p.pop();
if(v[now.x])continue;
v[now.x]=1;
d[now.x]=now.c;
for(int i=1;i<=n;i++)
{
int nex=(now.x+a[i]%a[1])%a[1];
if(d[nex]==0||d[nex]>now.c+a[i])
{
d[nex]=now.c+a[i];
p.push((lenka){nex,now.c+a[i]});
}
}
}
}
int main()
{
ll sum;
while(scanf("%lld%d",&sum,&n)!=EOF)
{
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
sort(a+1,a+n+1);
memset(d,0,sizeof d);
memset(v,0,sizeof v);
for(int i=1;i<=n;i++)p.push((lenka){(ll)a[i]%a[1],(ll)a[i]});
solve();
ll ans=min(sum%a[1],a[1]-sum%a[1]);
for(int i=0;i<a[1];i++)
{
if(d[i]==0)continue;
if(sum<=d[i])
{
ans=min(ans,sum%d[i]);
ans=min(ans,d[i]-sum%d[i]);
}
else
{
ll k=(sum-d[i])/a[1];
ans=min(ans,sum-(k*a[1]+d[i]));
ans=min(ans,abs(sum-((k+1)*a[1]+d[i])));
}
}
printf("%lld\n",ans);
}
return 0;
}