#include <bits/stdc++.h>
using namespace std;
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii ;
typedef pair<ll, ll> pll ;
typedef vector<pii> vii ;
typedef vector<int> veci ;
typedef vector<pll> vll ;
typedef vector<ll> vecll;
typedef unsigned short int sh;
// find_by_order order_of_key
//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt"
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define F first
#define S second
#define pb push_back
#define endl '\n'
#define Mp make_pair
#define all(x) x.begin(), x.end()
#define debug(x) cerr << #x << " = " << x << endl
#define set_dec(x) cout << fixed << setprecision(x);
#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define file_io freopen("in.txt" , "r" , stdin) ; freopen("out.txt" , "w" , stdout);
#define lb lower_bound
#define ub upper_bound
#define for1(n) for(int i=1;i<=n;i++)
#define for0(n) for(int i=0;i<n;i++)
#define forn(n) for(int i=n;i>0;i--)
#define pq priority_queue <pair<int,pii>, vector<pair<int,pii>>, greater<pair<int,pii>>>
int inf=1e9+10;
const int N=3e4+1,sq=250,sq2=125;
int n,m,k,dist1[N],dist[N][sq];
vector<int>g[N];
pii A[N];
pq q;
void ad(int x,int w){
if(x>=n || x<0)return;
if(dist1[x]>w){
dist1[x]=w;
q.push({w,{x,0}});
}
}
void add1(int x,int p,int w){
if(x>=n || x<0)return;
if(dist[x][p]>w){
dist[x][p]=w;
q.push({w,{x,p}});
}
}
void bfs(){
for0(n){
dist1[i]=inf;
for(int j=0;j<sq;j++)
dist[i][j]=inf;
}
dist1[A[0].F]=0;q.push({0,{A[0].F,0}});
while(q.size()){
int x=q.top().S.F,p=q.top().S.S,w=q.top().F;q.pop();
if(p==0){
if(dist1[x]!=w)continue;
for(int p:g[x]){
if(p<sq){
dist[x][p]=w;
q.push({w,{x,p}});
}
else{
for(int j=-sq2;j<=sq2;j++)
ad(x-p*j,w+abs(j));
}
}
}
else{
ad(x,w);
add1(x-p,p,w+1);
add1(x+p,p,w+1);
}
}
}
int32_t main(){
fast_io
cin>>n>>m;
for0(m){
int x,p;cin>>x>>p;
A[i]={x,p};
g[x].pb(p);
}
bfs();
if(dist1[A[1].F]==inf)return cout<<"-1\n",0;
cout<<dist1[A[1].F]<<endl;
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... |