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,target;
int pos[mxn],jump[mxn];
map<int,int>mp;
struct doge{
int cur;
int cnt;
bool vis[mxn];
doge(int cur_, int cnt_, vector<bool>v){
cur=cur_;
cnt=cnt_;
for(int i=0; i<sz(v); i++){
vis[i]=v[i];
}
}
bool operator < (const doge &rhs)const{
return cnt>rhs.cnt;
}
};
void solve(){
priority_queue<doge>pq;
vector<bool>vis(m);
vis[0]=1;
pq.push(doge(pos[0],0,vis));
while(!pq.empty()){
doge now = pq.top();
pq.pop();
int ind = mp[now.cur];
int jmp = jump[ind];
// to the left
for(int cor = now.cur-jmp,cnt=1; cor>=0; cor-=jmp, cnt++){
if(mp.count(cor)){
int visit = mp[cor];
if(visit==1){
cout << cnt+now.cnt << endl;
return;
}
if(!now.vis[visit]){
doge nxt = now;
nxt.cnt+=cnt;
nxt.cur=cor;
nxt.vis[visit]=1;
pq.push(nxt);
}
}
}
// to the right
for(int cor = now.cur+jmp,cnt=1; cor<n; cor+=jmp, cnt++){
if(mp.count(cor)){
int visit = mp[cor];
if(visit==1){
cout << cnt+now.cnt << endl;
return;
}
if(!now.vis[visit]){
doge nxt = now;
nxt.cnt+=cnt;
nxt.cur=cor;
nxt.vis[visit]=1;
pq.push(nxt);
}
}
}
}
cout << -1 << endl;
return;
}
int main()
{
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++){
cin >> pos[i] >> jump[i];
mp[pos[i]]=i;
}
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... |