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 fi first
#define se second
#define eb emplace_back
#define mt make_tuple
#define all(x) (x).begin(), (x).end()
#define sz(x) int(x.size())
#define MOD 1000000007
typedef long long ll;
typedef pair <int, int> ii;
typedef pair <ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef long double ld;
const ll INF=LLONG_MAX;
const int mxn=3e5+5;
bool DEBUG=0;
int n,m,start,target;
set<int>jumps[mxn];
void solve(){
priority_queue<ii,vector<ii>,greater<ii>>pq;
pq.push({0,start});
vi dist(n,INT_MAX);
while(!pq.empty()){
ii now = pq.top();
pq.pop();
int cost = now.fi;
int pos = now.se;
if(cost>dist[pos])continue;
dist[pos]=cost;
if(pos==target){
cout << cost << endl;
return;
}
//to the left
for(int jmp:jumps[pos]){
for(int cnt=1,cur=pos-jmp; cur>=0; cur-=jmp,cnt++){
if(dist[cur]>dist[pos]+cnt){
dist[cur]=dist[pos]+cnt;
pq.push({dist[cur],cur});
if(jumps[cur].count(jmp))break;
}
}
}
// to the right
for(int jmp:jumps[pos]){
for(int cnt=1,cur=pos+jmp; cur<n; cur+=jmp,cnt++){
if(dist[cur]>dist[pos]+cnt){
dist[cur]=dist[pos]+cnt;
pq.push({dist[cur],cur});
if(jumps[cur].count(jmp))break;
}
}
}
}
cout << -1 << endl;
return;
}
int main()
{
if(!DEBUG){ios_base::sync_with_stdio(0); cin.tie(0);}
//freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);
cin >> n >> m;
for(int i=0; i<m; i++){
int pos, jmp;
cin >> pos >> jmp;
jumps[pos].insert(jmp);
if(i==0)start=pos;
if(i==1)target=pos;
}
solve();
}
// READ & UNDERSTAND
// ll, int overflow, array bounds, memset(0)
// special cases (n=1?), n+1 (1-index)
// do smth instead of nothing & stay organized
// WRITE STUFF DOWN
# | 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... |