1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define maxn 30005 #define put() putchar('\n') #define Tp template<typename Ty> #define Ts template<typename Ty,typename... Ar> using namespace std; inline void read(int &x){ int f=1;x=0;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();} x*=f; } namespace Debug{ Tp void _debug(char* f,Ty t){cerr<<f<<'='<<t<<endl;} Ts void _debug(char* f,Ty x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);} Tp ostream& operator<<(ostream& os,vector<Ty>& V){os<<"[";for(auto& vv:V) os<<vv<<",";os<<"]";return os;} #define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__) }using namespace Debug; int n,m,b[maxn],p[maxn]; vector<int>O[maxn]; int head=1,h[maxn]; int pre[maxn],nex[maxn],t[maxn]; struct yyy{ int to,z,w; inline void add(int x,int y,int val) { to=y;z=h[x];h[x]=head;w=val; } }a[12000005]; int dis[maxn],vis[maxn]; #define mk make_pair #define fi first #define se second priority_queue<pair<int,int> >q; inline void dj(int s) { int i,x; memset(dis,0x3f,sizeof(dis)); q.push(mk(0,s));dis[s]=0; while (!q.empty()) { x=q.top().se;q.pop(); if (vis[x]) continue;vis[x]=1; for (i=h[x];i;i=a[i].z) if (dis[a[i].to]>dis[x]+a[i].w) { dis[a[i].to]=dis[x]+a[i].w; q.push(mk(-dis[a[i].to],a[i].to)); } } } signed main(void){ int i,j,k,o; read(m);read(n); for (i=1;i<=n;i++) read(b[i]),b[i]++,read(p[i]),O[p[i]].push_back(i); int block=sqrt(m)+1; for (j=1;j<=block;j++) { sort(O[j].begin(),O[j].end()); for (auto tmp:O[j]) t[b[tmp]]=1; for (k=1;k<=j;k++) { int las=k; for (i=k;i<=m;i+=j) pre[i]=las,las=(t[i]?i:las); i-=j;las=i; for (;i>=k;i-=j) nex[i]=las,las=(t[i]?i:las); for (i=k;i<=m;i+=j) if (t[i]) { for (o=pre[i];o<=nex[i];o+=j) if (i^o) a[++head].add(i,o,abs(i-o)/j); } } for (auto tmp:O[j]) t[b[tmp]]=0; } for (j=block+1;j<=m;j++) { for (auto tmp:O[j]) { for (i=b[tmp]-j;i>=1;i-=j) a[++head].add(b[tmp],i,abs(b[tmp]-i)/j); for (i=b[tmp]+j;i<=m;i+=j) a[++head].add(b[tmp],i,abs(b[tmp]-i)/j); } } int tmp=1; for (i=b[tmp]-j;i>=1;i-=j) a[++head].add(b[tmp],i,abs(b[tmp]-i)/p[tmp]); for (i=b[tmp]+j;i<=m;i+=j) a[++head].add(b[tmp],i,abs(b[tmp]-i)/p[tmp]); dj(b[1]); if (dis[b[2]]>1e9) puts("-1"); else printf("%d\n",dis[b[2]]); return 0; }
|