#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define pb push_back
#define ff first
#define ss second
const int inf = 1e9;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m; cin>>n>>m;
vector<int> x(m + 1), y(m + 1);
for (int i = 1; i <= m; i++){
cin>>x[i]>>y[i];
x[i]++;
}
vector<int> d[n + 1];
for (int i = 1; i <= m; i++) d[x[i]].pb(y[i]);
for (int i = 1; i <= n; i++) sort(d[i].begin(), d[i].end(), greater<int>());
queue<int> q; q.push(x[1]);
vector<int> out(n + 1, inf); out[x[1]] = 0;
while (!q.empty()){
int v = q.front(); q.pop();
for (int j: d[v]){
int f = v + j, cc = 1;
while (f <= n){
if (out[f] > (out[v] + cc)){
out[f] = out[v] + cc;
q.push(f);
}
f += j; cc++;
}
f = v - j; cc = 1;
while (f > 0){
if (out[f] > (out[v] + cc)){
out[f] = out[v] + cc;
q.push(f);
}
f -= j; cc++;
}
}
}
cout<<((out[x[2]] == inf) ? -1 : out[x[2]])<<"\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... |