// IN THE NAME OF GOD
#include<bits/stdc++.h>
using namespace std;
typedef long long int lli;
typedef pair<lli,lli> pii;
typedef vector<lli> ve;
typedef vector<pii> vp;
const lli N = 5e5 + 100;
const lli INF = 1e18;
const lli mod = 1e9 + 7;
#define PB push_back
#define MP make_pair
#define fi first
#define se second
#define FOR(x,y) for(lli x = 0; x < y; x ++)
#define FORS(x,y) for(lli x = 1; x <= y; x ++)
#define all(x) x.begin(),x.end()
#define lb lower_bound
#define ub upper_bound
#define debug(x) cerr<<(#x)<<" "<<x<<endl
lli n,m;
lli B[N],P[N];
vp adj[N];
lli dis[N];
ve hehe[N];
int main(){
	ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	cin>>n>>m;
	FOR(i,m){
		cin>>B[i]>>P[i];
		hehe[B[i]].PB(i);
	}
	FOR(a,m){
		for(lli i = B[a]%P[a]; i < n;i += P[a]){
			for(lli b : hehe[i]){
				lli fa = abs(B[b]-B[a]);
				adj[a].PB(MP(b,fa/P[a]));
				adj[b].PB(MP(b,2*(fa/P[a]) ));
			}
		}
	}
	FOR(i,m)
		dis[i] = INF;
	priority_queue<pii,vp,greater<pii>> pq;
	pq.push(MP(0,0));
	dis[0] = 0;
	while(pq.size()){
		lli v = pq.top().se;
		lli D = pq.top().fi;
		pq.pop();
		if(D != dis[v])continue;
		for(auto [u,w] : adj[v]){
			if(dis[u] > dis[v] + w){
				dis[u] = dis[v] + w;
				pq.push(MP(dis[u],u));
			}
		}
	}
	if(dis[1] == INF)dis[1] = -1;
	cout<<dis[1]<<endl;
}
| # | 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... |