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;
const int SQRT = 175;
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 s = 0, t = 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) {
s = b;
}
if (i == 1) {
t = b;
}
}
if (s == t) {
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<pair<int, int>> q;
vector<vector<int>> dp(n, vector<int>(SQRT, INF));
vector<vector<bool>> inQ(n, vector<bool>(SQRT));
dp[s][0] = 0;
q.emplace(s, 0);
inQ[s][0] = true;
while (!q.empty()) {
int u, p;
tie(u, p) = q.front();
q.pop();
inQ[u][p] = false;
if (p == 0) {
for (int pp : g[u]) {
if (pp < SQRT) {
if (dp[u][pp] > dp[u][0]) {
dp[u][pp] = dp[u][0];
if (!inQ[u][pp]) {
q.emplace(u, pp);
}
}
} else {
int cost = 0;
for (int v = u - pp; v >= 0; v -= pp) {
cost += 1;
if (dp[v][0] > dp[u][0] + cost) {
dp[v][0] = dp[u][0] + cost;
if (!inQ[v][0]) {
q.emplace(v, 0);
}
}
}
cost = 0;
for (int v = u + pp; v < n; v += pp) {
cost += 1;
if (dp[v][0] > dp[u][0] + cost) {
dp[v][0] = dp[u][0] + cost;
if (!inQ[v][0]) {
q.emplace(v, 0);
}
}
}
}
}
} else {
if (dp[u][0] > dp[u][p]) {
dp[u][0] = dp[u][p];
if (!inQ[u][0]) {
q.emplace(u, 0);
}
}
for (int sgn : {-1, 1}) {
int v = u + sgn * p;
if (0 <= v && v < n && dp[v][p] > dp[u][p] + 1) {
dp[v][p] = dp[u][p] + 1;
if (!inQ[v][p]) {
q.emplace(v, p);
}
}
}
}
}
if (dp[t][0] == INF) {
cout << "-1\n";
} else {
cout << dp[t][0] << '\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... |