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;
int main()
{
cin.tie(0); ios_base::sync_with_stdio(0);
int n, m;
cin >> n >> m;
vector<int> g[n + 1], p(m), x(m);
for(int i = 0; i < m; i++) {
cin >> x[i] >> p[i];
g[x[i]].push_back(i);
}
queue<pair<int,int>> q;
vector<vector<int>> dist(n + 1, vector<int>(n + 1, -1));
q.push({x[0], p[0]});
dist[x[0]][p[0]] = 0;
while(!q.empty()) {
auto [v, pow] = q.front(); q.pop();
// cout << v << " " << pow << " " << dist[v][pow] << '\n';
if(v - pow >= 0 && dist[v - pow][pow] == -1) {
q.push({v - pow, pow});
dist[v - pow][pow] = dist[v][pow] + 1;
}
if(v + pow < n && dist[v + pow][pow] == -1) {
q.push({v + pow, pow});
dist[v + pow][pow] = dist[v][pow] + 1;
}
int d = dist[v][pow];
for(auto idx : g[v]) {
dist[v][p[idx]] = d;
if(v - p[idx] >= 0 && dist[v - p[idx]][p[idx]] == -1) {
q.push({v - p[idx], p[idx]});
dist[v - p[idx]][p[idx]] = dist[v][p[idx]] + 1;
}
if(v + p[idx] < n && dist[v + p[idx]][p[idx]] == -1) {
q.push({v + p[idx], p[idx]});
dist[v + p[idx]][p[idx]] = dist[v][p[idx]] + 1;
}
}
}
int ans = 1e9;
for(int i = 0; i < n; i++) {
if(dist[x[1]][i] != -1) ans = min(ans, dist[x[1]][i]);
}
cout << (ans == 1e9 ? -1 : ans);
}
# | 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... |