#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n , m;
cin >> n >> m;
vector<pair<int,int>> cost(n , {0 , 0});
vector<int> id(m);
vector<bool> have(n);
for(int i = 0 ; i < m ; i++){
int a , b;
cin >> a >> b;
have[a] = true;
cost[a] = make_pair(b , i);
id[i] = b;
}
if(!have[0] || n == 1){
cout << -1 << '\n';
return 0;
}
// assert that 0 has a cost
vector<vector<int>> dist(n , vector<int>(m , (int)1e9));
vector<vector<bool>> vis(n , vector<bool>(m));
vis[0][cost[0].second] = true;
priority_queue<pair<int,pair<int,int>> , vector<pair<int,pair<int,int>>> , greater<pair<int,pair<int,int>>>> pq;
dist[0][cost[0].second] = 0;
auto is_right = [&](int node , int idx){
return node >= 0 && node < n && !vis[node][idx];
};
pq.emplace(0 , make_pair(0 , cost[0].second));
while(!pq.empty()){
auto f = pq.top();
pq.pop();
if(f.first != dist[f.second.first][f.second.second]) continue;
for(int i = 0 ; i < 2 ; i++){
int cur = (i ? 1 : -1);
int who = f.second.first + cur * id[f.second.second];
if(!is_right(who , f.second.second)) continue;
if(dist[who][f.second.second] > f.first + 1){
dist[who][f.second.second] = f.first + 1;
pq.emplace(dist[who][f.second.second] , make_pair(who , f.second.second));
if(!vis[who][cost[who].second] && cost[who].second != 0) {
dist[who][cost[who].second] = dist[who][f.second.second];
pq.emplace(dist[who][f.second.second] , make_pair(who , cost[who].second));
vis[who][cost[who].second] = true;
}
vis[who][f.second.second] = true;
}
}
}
int best = (int)1e9;
for(int i = 0 ; i < m ; i++){
best = min(best , dist[1][i]);
}
if(best == (int)1e9){
cout << -1 << '\n';
}
else cout << best << '\n';
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
204 KB |
Output is correct |
2 |
Incorrect |
0 ms |
204 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
204 KB |
Output is correct |
2 |
Incorrect |
0 ms |
204 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
204 KB |
Output is correct |
2 |
Incorrect |
0 ms |
204 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
204 KB |
Output is correct |
2 |
Incorrect |
0 ms |
204 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
204 KB |
Output is correct |
2 |
Incorrect |
1 ms |
204 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |