This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define dbg(x) x
#define prt(x) dbg(cerr << x)
#define pv(x) dbg(cerr << #x << " = " << x << '\n')
#define pv2(x) dbg(cerr << #x << " = " << x.first << ',' << x.second << '\n')
#define parr(x) dbg(prt(#x << " = { "); for (auto y : x) prt(y << ' '); prt("}\n");)
#define parr2(x) dbg(prt(#x << " = { "); for (auto [y, z] : x) prt(y << ',' << z << " "); prt("}\n");)
#define parr2d(x) dbg(prt(#x << ":\n"); for (auto arr : x) {parr(arr);} prt('\n'));
#define parr2d2(x) dbg(prt(#x << ":\n"); for (auto arr : x) {parr2(arr);} prt('\n'));
/*
can jump only multiples of 1 number
get from p0 to p1
can only jump if 0 or it was passed to you
everyone will only have it once?
can add o(m^2) edges and run dijkstra
alternatively, can add o(n^2) edges
*/
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n, m;
cin >> n >> m;
vector<int> a(m), b(m);
vector<vector<array<int, 2>>> edges(n);
for (int i = 0; i < m; i++) {
cin >> a[i] >> b[i];
for (int j = a[i] + b[i]; j < n; j += b[i]) {
edges[a[i]].push_back({j, (j - a[i]) / b[i]});
}
for (int j = a[i] - b[i]; j >= 0; j -= b[i]) {
edges[a[i]].push_back({j, (a[i] - j) / b[i]});
}
}
priority_queue<array<int, 2>> q;
vector<int> dist(n, 1e9);
dist[a[0]] = 0;
q.push({0, a[0]});
while (q.size()) {
int d = -q.top()[0], node = q.top()[1];
q.pop();
if (d != dist[node]) continue;
for (auto [next, wt] : edges[node]) {
if (dist[node] + wt < dist[next]) {
dist[next] = dist[node] + wt;
q.push({-dist[next], next});
}
}
}
cout << (dist[a[1]] == 1e9 ? -1 : dist[a[1]]) << '\n';
}
/*
any observations help
check every line
IF YOUR LINES AREN'T WRONG
CHECK IF YOUR LINES ARE IN THE RIGHT ORDER
NEVER GIVE UP
*/
# | 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... |