#include <bits/stdc++.h>
#define sz(a) (int)a.size()
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define int long long
using namespace std;
signed main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr);
int N,M; cin >> N >> M;
vector<vector<int>> neigh(N);
int sb=-1,se=-1;
for (int i = 0; i < M; i++)
{
int B,P; cin >> B >> P;
if(sb==-1) sb=B;
else if(se==-1) se=B;
neigh[B].push_back(P);
}
int sq=sqrt(N);
vector<vector<int>> dist(N,vector<int>(sq,1e17));
vector<vector<int>> visited(N,vector<int>(sq,0));
priority_queue<pair<int,pair<int,int>>> q;
q.push({0,{sb,0}});
dist[sb][0]=0;
while(!q.empty()){
int x=q.top().second.first,s=q.top().second.second; q.pop();
if(visited[x][s]) continue;
visited[x][s]=true;
int d=dist[x][s];
if(s>0){
if(x-s>=0) {
if(dist[x-s][s]>d+1){
dist[x-s][s]=d+1;
q.push({-(d+1),{x-s,s}});
}
}
if(x+s<N){
if(dist[x+s][s]>d+1){
dist[x+s][s]=d+1;
q.push({-(d+1),{x+s,s}});
}
}
}
for (auto u : neigh[x])
{
if(u==s) continue;
if(u>=sq){
int c=d+1;
for (int j = x+u; j < N; j+=u)
{
if(dist[j][0]>c){
dist[j][0]=c;
q.push({-(c),{j,0}});
}
c++;
}
c=d+1;
for (int j = x-u; j >= 0; j-=u)
{
if(dist[j][0]>c){
dist[j][0]=c;
q.push({-(c),{j,0}});
}
c++;
}
}else{
if(x-u>=0) {
if(dist[x-u][u]>d+1){
dist[x-u][u]=d+1;
q.push({-(d+1),{x-u,u}});
}
}
if(x+u<N){
if(dist[x+u][u]>d+1){
dist[x+u][u]=d+1;
q.push({-(d+1),{x+u,u}});
}
}
}
}
}
int mn=1e17;
for (int j = 0; j < sq; j++)
{
mn=min(dist[se][j],mn);
}
if(mn==1e17) cout << -1 << "\n";
else cout << mn << "\n";
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... |