#ifdef t9unkubj
#define _GLIBCXX_DEBUG
#include"debug.cpp"
//#include"template_no_debug.h"
#else
#define dbg(...) 199958
#endif
#pragma GCC optimize("O3")
using namespace std;
#include<bits/stdc++.h>
using ll=long long;
using ull=unsigned long long;
template<class T>using vc=vector<T>;
template<class T>using vvc=vc<vc<T>>;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define REP(i,j,n) for(ll i=(j);i<(ll)(n);i++)
#define DREP(i,n,m) for(ll i=(n);i>=(m);i--)
#define drep(i,n) for(ll i=((n)-1);i>=0;i--)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
template<class T,class F>
bool chmin(T &x, F y){
if(x>y){
x=y;
return true;
}
return false;
}
template<class T, class F>
bool chmax(T &x, F y){
if(x<y){
x=y;
return true;
}
return false;
}
double pass_time=0;
void solve(){
int n,m;
cin>>n>>m;
vc<int>b(m),p(m);
rep(i,m)cin>>b[i]>>p[i];
vvc<int>is(n);
rep(i,m){
is[b[i]].push_back(i);
}
constexpr int B=300;
vvc<int>md(n,vc<int>(B+1,1e9));
using T=array<int,3>;
//最短距離,頂点,とび幅
priority_queue<T,vc<T>,greater<>>que;
//(pos,d)から飛ばせる
auto update=[&](int pos,int d,int D){
if(chmin(md[pos][d],D)){
que.push({md[pos][d],pos,d});
}
};
auto apply=[&](int pos,int d,int T){
{
assert(d<B);
if(pos-d>=0)update(pos-d,d,T+1);
if(pos+d<n)update(pos+d,d,T+1);
update(pos,B,T);
}
};
update(b[0],B,0);
while(que.size()){
auto [D,pos,d]=que.top();que.pop();
if(md[pos][d]!=D)continue;
if(d<B){
apply(pos,d,md[pos][d]);
}else{
for(auto&i:is[pos]){
if(p[i]>=B){
for(int now=pos%p[i];now<n;now+=p[i]){
update(now,B,abs(pos-now)/p[i]+md[pos][d]);
}
}else{
apply(pos,p[i],md[pos][B]);
}
}
}
}
ll ans=md[b[1]][B];
if(ans>1e8)cout<<"-1\n";
else cout<<ans<<"\n";
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
pass_time=clock();
int t=1;
//cin>>t;
while(t--)solve();
pass_time=clock()-pass_time;
dbg(pass_time/CLOCKS_PER_SEC);
}
/*
5 3
0 2
1 1
4 1
*/
# | 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... |