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>
#define INF 0x3f3f3f3f
using namespace std;
void minSelf(int &x, int y) {
if (y < x) {
x = y;
}
}
void testCase() {
int n, m;
cin >> n >> m;
vector<vector<int>> g(n);
int source = 0, sink = 0;
for (int i = 0; i < m; ++i) {
int b, p;
cin >> b >> p;
if (0 <= b - p || b + p < n) {
g[b].emplace_back(p);
}
if (i == 0) {
source = b;
}
if (i == 1) {
sink = b;
}
}
if (source == sink) {
cout << "0\n";
return;
}
for (int v = 0; v < n; ++v) {
sort(g[v].begin(), g[v].end());
g[v].erase(unique(g[v].begin(), g[v].end()), g[v].end());
}
queue<tuple<int, int, int>> q;
unordered_set<int> vis;
vector<bool> mark(n);
int best = INF;
auto convert = [&](int x, int y) -> int {
return x * n + y;
};
for (int p : g[source]) {
q.emplace(0, source, p);
vis.emplace(convert(source, p));
mark[0] = true;
}
while (!q.empty()) {
int cost, u, p;
tie(cost, u, p) = q.front();
q.pop();
if (u == sink) {
minSelf(best, cost);
}
if (!mark[u]) {
for (int pp : g[u]) {
int state = convert(u, pp);
if (!vis.count(state)) {
vis.emplace(state);
q.emplace(cost, u, pp);
}
}
mark[u] = true;
}
for (int sgn : {-1, 1}) {
int v = u + sgn * p;
if (0 <= v && v < n) {
int state = convert(v, p);
if (!vis.count(state)) {
vis.emplace(state);
q.emplace(cost + 1, v, p);
}
}
}
}
if (best == INF) {
cout << "-1\n";
} else {
cout << best << '\n';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int tests = 1;
for (int tc = 0; tc < tests; ++tc) {
testCase();
}
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... |