#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e9+7;
const ll MOD = 998244353;
typedef pair<ll,ll> ii;
#define iii pair<ii,ll>
#define f(i,a,b) for(ll i = a;i < b;i++)
#define pb push_back
#define vll vector<ll>
#define F first
#define S second
#define all(x) (x).begin(), (x).end()
///I hope I will get uprating and don't make mistakes
///I will never stop programming
///sqrt(-1) Love C++
///Please don't hack me
///@TheofanisOrfanou Theo830
///Think different approaches (bs,dp,greedy,graphs,shortest paths,mst)
///Stay Calm
///Look for special cases
///Beware of overflow and array bounds
///Think the problem backwards
///Training
int main(void){
ios_base::sync_with_stdio(0);
cin.tie(0);
ll n,m;
cin>>n>>m;
ll b[m],p[m];
f(i,0,m){
cin>>b[i]>>p[i];
}
bool done[m] = {0};
ll dist[m];
f(i,0,m){
dist[i] = INF;
}
dist[0] = 0;
ll ek = m;
while(ek--){
ll mini = INF+1;
ll pos = -1;
f(i,0,m){
if(!done[i] && mini > dist[i]){
pos = i;
mini = dist[i];
}
}
done[pos] = 1;
f(i,0,m){
if(!done[i]){
ll dista = abs(b[pos] - b[i]);
if(dista % p[pos] == 0){
dist[i] = min(dist[i],mini + dista / p[pos]);
}
}
}
}
ll ans = INF;
ll best[n];
f(i,0,n){
best[i] = INF;
}
f(i,0,m){
ll cur = b[i];
ll posa = 0;
while(cur < n){
best[cur] = min(best[cur],dist[i] + posa);
cur += p[i];
posa++;
}
cur = b[i];
posa = 0;
while(cur >= 0){
best[cur] = min(best[cur],dist[i] + posa);
cur -= p[i];
posa++;
}
}
ans = best[b[1]];
if(ans == INF){
ans = -1;
}
cout<<ans<<"\n";
}
# | 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... |