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;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
#define all(x) (x).begin(),(x).end()
#define X first
#define Y second
#define sep ' '
#define endl '\n'
#define SZ(x) ll(x.size())
const ll MAXN = 3e4 + 10;
const ll SQ = 200;
const ll LOG = 22;
const ll INF = 8e18;
const ll MOD = 1e9 + 7; //998244353; //1e9 + 9;
int n , m , ptr;
int q[MAXN * SQ * 4] , dist[MAXN * SQ * 2] , pos[MAXN * SQ * 2] , len[MAXN * SQ * 2];
vector<int> adj[MAXN];
void BFS(int v){
fill(dist , dist + MAXN * SQ * 2 , MOD);
dist[v] = 0;
int ql = MAXN * SQ * 2 , qr = ql;
q[qr++] = v;
while(ql < qr){
int v = q[ql++];
if(v < n){
for(int u : adj[v]){
if(dist[u] > dist[v]){
dist[u] = dist[v];
q[--ql] = u;
}
}
continue;
}
if(dist[pos[v]] > dist[v]){
dist[pos[v]] = dist[v];
q[--ql] = pos[v];
}
if(v < n + m) continue;
for(int i = -1 ; i <= 1 ; i += 2){
int u = v + i * (len[v] < 0 ? -1 : len[v]) , p = pos[v] + i * len[v];
if(p < 0 || p >= n) continue;
if(dist[u] > dist[v] + 1){
dist[u] = dist[v] + 1;
q[qr++] = u;
}
}
}
}
int main() {
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin >> n >> m;
ptr = n + m;
for(int i = 1 ; i < SQ ; i++){
for(int j = 0 ; j < n ; j++){
pos[ptr + j] = j;
len[ptr + j] = i;
}
ptr += n;
}
for(int i = 0 ; i < m ; i++){
int x , y;
cin >> x >> y;
adj[x].push_back(n + i);
if(y < SQ){
pos[n + i] = m + n * y + x;
continue;
}
int z = x % y;
for(int j = z ; j < n ; j += y){
pos[ptr] = j;
len[ptr] = -y;
if(j == x){
pos[n + i] = ptr;
}
ptr++;
}
}
BFS(n);
cout << (dist[n + 1] == MOD ? -1 : dist[n + 1]) << endl;
return 0;
}
/*
*/
# | 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... |