728x90
반응형
https://www.acmicpc.net/problem/23793
23793번: 두 단계 최단 경로 1
서준이는 아빠로부터 생일선물로 세계 지도를 받아서 매우 기뻤다. 세계 지도에서 최단 경로를 찾는 프로그램을 개발해서 아빠께 감사의 마음을 전달하려고 한다. 세계 지도는 도시를 정점으
www.acmicpc.net
#include <iostream>
#include <vector>
#include <queue>
#define INF 2e9
#define MAX 100001
#define MAX_EDGE 200001
using namespace std;
int n, m, x, y, z;
int d[MAX];
vector<pair<int, int>> v[MAX_EDGE];
void dijkstra(int start){
for(int i = 0; i <= n; i++)
d[i] = INF;
d[start] = 0;
priority_queue<pair<int, int>> pq;
pq.push({0, start});
while(!pq.empty()){
int cur = pq.top().second;
int start_to_cur_dis = -pq.top().first;
pq.pop();
if(d[cur] < start_to_cur_dis) continue;
for(int i = 0; i < v[cur].size(); i++){
int next = v[cur][i].second;
int start_to_next_dis = start_to_cur_dis + v[cur][i].first;
if(d[next] > start_to_next_dis){
d[next] = start_to_next_dis;
pq.push({-start_to_next_dis, next});
}
}
}
}
void dijkstra2(int start){
for(int i = 0; i <= n; i++)
d[i] = INF;
d[start] = 0;
priority_queue<pair<int, int>> pq;
pq.push({0, start});
while(!pq.empty()){
int cur = pq.top().second;
int start_to_cur_dis = -pq.top().first;
pq.pop();
if(d[cur] < start_to_cur_dis) continue;
for(int i = 0; i < v[cur].size(); i++){
int next = v[cur][i].second;
int start_to_next_dis = start_to_cur_dis + v[cur][i].first;
if(next == y) continue;
if(d[next] > start_to_next_dis){
d[next] = start_to_next_dis;
pq.push({-start_to_next_dis, next});
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for(int i = 0; i < m; i++){
int a, b, c;
cin >> a >> b >> c;
v[a].push_back({c, b});
}
cin >> x >> y >> z;
dijkstra(x);
int t = d[y];
dijkstra(y);
if(t == INF || d[z] == INF) cout << -1 << " ";
else cout << t + d[z] << " ";
dijkstra2(x);
if(d[z] == INF) cout << -1 << endl;
else cout << d[z] << endl;
return 0;
}
1. Y를 거쳐가는 경우(dijkstra)
(x → y 최단거리) + (y → z 최단거리)로 나눌 수 있다. x를 시작점으로 dijkstra를 돌려서 나오는 d[y]값, y를 시작점으로 dijkstra를 돌려서 나오는 d[z]값을 더한다.
2. Y를 거치지 않는 경우(dijkstra2)
next가 y일 경우 해당 간선 추가 작업을 수행하지 않고 넘어가도록 한다.
*) 처음에 INF를 987654321로 설정하여 틀렸는데 2e9로 바꾼 뒤 AC를 받았다.
728x90
반응형
'Algorithm > BAEKJOON' 카테고리의 다른 글
[BOJ] 15681번 트리와 쿼리 (C++) (0) | 2022.08.07 |
---|---|
[BOJ] 1245번 농장 관리 (C++) (0) | 2022.08.07 |
[BOJ] 1238번 파티 (C++) (0) | 2022.08.05 |
[BOJ] 11779번 최소비용 구하기 2 (C++) (0) | 2022.08.04 |
[BOJ] 9694번 무엇을 아느냐가 아니라 누구를 아느냐가 문제다 (C++) (0) | 2022.08.04 |