This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "bits/stdc++.h"
using namespace std;
#define double long double
const int MAXN = 9500000;
const int MOD = 1e9 + 7;
mt19937_64 rng((int)std::chrono::steady_clock::now().time_since_epoch().count());
int rnd(int x, int y) {
int u = uniform_int_distribution<int>(x, y)(rng); return u;
}
int bm(int b, int p) {
if(p==0) return 1 % MOD;
int r = bm(b, p >> 1);
if(p&1) return (((r*r) % MOD) * b) % MOD;
return (r*r) % MOD;
}
int inv(int b) {
return bm(b, MOD-2);
}
int fastlog(int x) {
return (x == 0 ? -1 : 64 - __builtin_clzll(x) - 1);
}
void printcase(int i) { cout << "Case #" << i << ": "; }
vector<int>adj[MAXN];
void solve(int tc) {
int n, m;
cin >> n >> m;
int s = sqrt(n);
int nxt = (s+1) * n;
for(int i=1; i<=s; i++) {
for(int j=i*n; j<(i+1)*n; j++) {
if(j+i < (i+1)*n) adj[j].push_back((j+i) * 2 + 1);
if(j-i >= i*n) adj[j].push_back((j-i) * 2 + 1);
adj[j].push_back((j%n) * 2 + 0);
}
}
int st, en;
for(int i=0; i<m; i++) {
int b, p;
cin >> b >> p;
if(i == 0) st = b;
if(i == 1) en = b;
if(p <= s) adj[b].push_back((b+p*n) * 2 + 0);
else {
for(int j=b%p; j<n; j+=p) {
if(j+p < n) adj[nxt + j/p].push_back((nxt + j/p + 1) * 2 + 1);
if(j-p >= 0) adj[nxt + j/p].push_back((nxt + j/p - 1) * 2 + 1);
adj[nxt + j/p].push_back(j * 2 + 0);
}
adj[b].push_back((nxt + b/p) * 2 + 0);
for(int j=b%p; j<n; j+=p) {
nxt++;
}
}
}
int k = nxt;
int dist[k];
bool vis[k];
for(int i=0; i<k; i++) dist[i] = 1e9, vis[i] = 0;
dist[st] = 0;
deque<int> dq;
dq.push_back(st);
while(dq.size()) {
int f = dq.front();
dq.pop_front();
if(!vis[f]) {
vis[f] = 1;
for(int x: adj[f]) {
if(!vis[x / 2] && dist[x / 2] > dist[f] + (x % 2)) {
dist[x / 2] = dist[f] + (x % 2);
if(x % 2 == 0) dq.push_front(x / 2);
else dq.push_back(x / 2);
}
}
}
}
cout<<(dist[en]==1e9?-1:dist[en])<<"\n";
}
int32_t main() {
ios::sync_with_stdio(0); cin.tie(0);
int t = 1; //cin >> t;
for(int i=1; i<=t; i++) solve(i);
}
// 勿忘初衷
Compilation message (stderr)
skyscraper.cpp: In function 'void solve(int)':
skyscraper.cpp:76:17: warning: 'en' may be used uninitialized in this function [-Wmaybe-uninitialized]
76 | cout<<(dist[en]==1e9?-1:dist[en])<<"\n";
| ~~~~~~~^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |