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 = 1e4 + 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 , q[MAXN * SQ * 4] , dist[MAXN * SQ * 2];
vector<int> adj[MAXN * SQ * 2];
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++];
for(int u : adj[v]){
int cost = (v >= n + m && u >= n + m);
if(dist[u] > dist[v] + cost){
dist[u] = dist[v] + cost;
if(cost == 0) q[--ql] = u;
else 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 + i < n ; j++){
adj[ptr + j].push_back(ptr + j + i);
adj[ptr + j + i].push_back(ptr + j);
}
for(int j = 0 ; j < n ; j++){
adj[ptr + j].push_back(j);
}
ptr += n;
}
for(int i = 0 ; i < m ; i++){
int x , y;
cin >> x >> y;
adj[x].push_back(n + i);
if(y < SQ){
adj[n + i].push_back(m + n * y + x);
continue;
}
int z = x % y;
for(int j = z ; j < n ; j += y){
if(j + y < n){
adj[ptr].push_back(ptr + 1);
adj[ptr + 1].push_back(ptr);
}
adj[ptr].push_back(j);
if(j == x){
adj[n + i].push_back(ptr);
}
ptr++;
}
}
BFS(n);
/*for(int i = 0 ; i < ptr ; i++){
cout << i << sep << dist[i] << endl;
}*/
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... |