#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 <pii, vector<pii>, greater<pii>>
int inf=1e9+10;
const int N=3e4+1;
int n,m,k;
unordered_map<int,int> dist[N];
vector<int>g[N];
pii A[N];
deque<pii>q;
void add1(int x,int p,int w){
if(dist[x].find(p)==dist[x].end())dist[x][p]=inf;
if(dist[x][p]<=w)return;
dist[x][p]=w;
q.push_front({x,p});
}
void add2(int x,int p,int w){
if(dist[x].find(p)==dist[x].end())dist[x][p]=inf;
if(dist[x][p]<=w+1)return;
dist[x][p]=w+1;
q.pb({x,p});
}
void bfs(){
dist[A[0].F][A[0].S]=0;q.pb(A[0]);
while(q.size()){
int x=q.front().F,p=q.front().S;q.pop_front();
int w=dist[x][p];
short int t=ub(all(g[x]),p)-g[x].begin();
if(t!=g[x].size())
add1(x,g[x][t],w);
t=lb(all(g[x]),p)-g[x].begin()-1;
if(t!=-1)
add1(x,g[x][t],w);
if(x-p>=0)
add2(x-p,p,w);
if(x+p<n)
add2(x+p,p,w);
}
}
int32_t main(){
fast_io
cin>>n>>m;
for0(m){
int x,p;cin>>x>>p;
A[i]={x,p};
g[x].pb(p);
}
for0(n){sort(all(g[i]));g[i].resize(unique(all(g[i]))-g[i].begin());}
bfs();
if(dist[A[1].F].find(A[1].S)==dist[A[1].F].end())return cout<<"-1\n",0;
cout<<dist[A[1].F][A[1].S]<<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... |