#include <bits/stdc++.h>
#define hash _hash_
#define left _left_
#define y1 _y1_
using namespace std;
using ll = long long;
const ll MOD = 1e9 + 7;
const ll oo = 1e9;
/*----------- I alone decide my fate! ----------*/
/* Chiec den ong sao, sao 5 canh tuoi mau */
const int sqrtt = 200;
int N, M, a[30009], st, dist[30009];
int p[30009];
vector <int> rem[209][209], pos[30009];
void Dijkstra() {
for (int i = 1; i <= N; i ++) dist[i] = 1e9;
priority_queue <pair <int, int>, vector <pair <int ,int> >, greater <pair <int, int> > > pq;
pq.push({0, 0});
while (!pq.empty()) {
pair <int, int> top = pq.top();
pq.pop();
int u = top.second, cost = top.first;
if (a[u] == a[1]) {
cout << cost; return;
}
if (dist[u] < cost) continue;
if (p[u] <= sqrtt) {
for (auto v : rem[p[u]][a[u] % p[u]]) {
if (dist[v] > dist[u] + abs(a[u] - a[v])/p[u]) {
dist[v] = dist[u] + abs(a[u] - a[v])/p[u];
pq.push({dist[v], v});
}
}
}
else {
for (int i = a[u] % p[u]; i <= N; i += p[u]) {
for (auto v : pos[i]) {
if (dist[v] > dist[u] + abs(a[u] - a[v])/p[u]) {
dist[v] = dist[u] + abs(a[u] - a[v])/p[u];
pq.push({dist[v], v});
}
}
}
}
}
cout << -1;
}
void solve() {
cin >> N >> M;
for (int i = 0; i < M; i ++) {
cin >> a[i] >> p[i];
for (int j = 1; j <= sqrtt; j ++) {
rem[j][a[i] % j].push_back(i);
}
if (i == 0) st = a[i];
pos[a[i]].push_back(i);
}
Dijkstra();
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(nullptr);
solve();
return 0;
}
/*
How can you see into my eyes, like open doors?
Leading you down into my core, where I've become so numb
Without a soul, my spirit's sleeping somewhere cold
Until you find it here and bring it back home!
Wake me up! Wake me up inside
Cant wake up? Wake me up inside
*/
# | 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... |