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