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 <iostream>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;
#define MAXN 30005
#define INF 1000000009
#define pii pair<int, int>
#define mp make_pair
#define f first
#define s second
int n, m;
int b[MAXN];
int p[MAXN];
int dist[MAXN];
set<int> jumpsset[MAXN];
vector<int> jumps[MAXN];
void solve(int s) {
dist[b[0]] = 0;
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push(mp(0,b[0]));
while (!pq.empty()) {
pii node = pq.top();
pq.pop();
if (node.f > dist[node.s]) {
continue;
}
for(auto jump : jumps[node.s]) {
for (int j = 1; node.s + jump * j < n; ++j) { // forward
if (dist[node.s + jump * j] > node.f + j) {
dist[node.s + jump * j] = node.f + j;
pq.push(mp(node.f + j, node.s + jump * j));
if (binary_search(jumps[node.s + jump * j].begin(), jumps[node.s + jump * j].end(), jump)) { // no need to have multiple doges going same "route"
break;
}
}
}
for (int j = 1; node.s - jump * j >= 0;++j) { // backward
if (dist[node.s - jump * j] > node.f + j) {
dist[node.s - jump * j] = node.f + j;
pq.push(mp(node.f + j, node.s - jump * j));
if (binary_search(jumps[node.s - jump * j].begin(), jumps[node.s - jump * j].end(), jump)) {
break;
}
}
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for(int i = 0; i < m; ++i) {
cin >> b[i] >> p[i];
jumpsset[b[i]].insert(p[i]);
}
for(int i = 0; i < n; ++i) {
for(auto jump : jumpsset[i]) {
jumps[i].push_back(jump);
}
}
for(int i = 0; i <= n; ++i) {
dist[i] = INF;
}
solve(b[0]);
if (dist[b[1]] == INF) {
cout << "-1" << endl;
return 0;
}
cout << dist[b[1]] << 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... |