没判重点一直炸qwq
这题看起来就很最短路
但是直接建边明显不行
注意到当p>
n√
时边数是
n√
的,总边数
nn√
当p<
n√
时,可以发现对于p相同,mod p下相同的两个
点我们会建重复很多边
具体来说,如果有x< y,px=py, x%p=y%p,那么x连到y右边的j边可以通过x->y->j,x只需要连到y就好了
那么这样的总边数是
p∗n/p∗n√=nn√
的
于是就把边数弄到了
nn√
级别
然后跑dijstra就行了
code:
#include<set>
#include<map>
#include<deque>
#include<queue>
#include<stack>
#include<cmath>
#include<ctime>
#include<bitset>
#include<string>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<climits>
#include<complex>
#include<iostream>
#include<algorithm>
#define ll long long
#define inf 1e9
using namespace std;
const int maxn = 31000;
const int maxm = maxn*420;
int n,m,st,ed;
struct node{int p,c;}a[maxn];
inline bool cmpc(const node x,const node y){return x.c==y.c?x.p<y.p:x.c<y.c;}
int vi[maxn];
struct edge{int y,c,nex;}e[maxm]; int len,fir[maxn];
inline void ins(const int x,const int y,const int c){e[++len]=(edge){y,c,fir[x]};fir[x]=len;}
int f[maxn];
struct pq{int x,i;};
inline bool operator <(const pq &x,const pq &y){return x.x>y.x;}
priority_queue<pq>q;
void dij()
{
for(int i=1;i<=n;i++) f[i]=inf;
f[st]=0; q.push((pq){0,st});
while(!q.empty())
{
const pq now=q.top(); q.pop();
if(now.x!=f[now.i]) continue;
const int x=now.i;
for(int k=fir[x],y=e[k].y;k;k=e[k].nex,y=e[k].y)
if(f[y]>f[x]+e[k].c) f[y]=f[x]+e[k].c,q.push((pq){f[y],y});
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++) scanf("%d%d",&a[i].p,&a[i].c),a[i].p++;
st=a[1].p,ed=a[2].p;
sort(a+1,a+m+1,cmpc);
for(int i=1;i<=m;)
{
int j=i;for(;j<=m&&a[j].c==a[i].c;j++)vi[a[j].p]=a[i].c; j--;
for(;i<=j;i++)
{
if(a[i].p==a[i-1].p&&a[i].c==a[i-1].c) continue;
int kk=a[i].p-a[i].c;
for(int ti=1;kk>0;kk-=a[i].c,ti++)
{
ins(a[i].p,kk,ti);
if(vi[kk]==a[i].c) break;
}
kk=a[i].p+a[i].c;
for(int ti=1;kk<=n;kk+=a[i].c,ti++)
{
ins(a[i].p,kk,ti);
if(vi[kk]==a[i].c) break;
}
}
}
dij();
if(f[ed]==inf) f[ed]=-1;
printf("%d\n",f[ed]);
return 0;
}