https://www.acmicpc.net/problem/1504

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int INF = 1000000000 / 3;
// N: 정점의 개수, E: 간선의 개수
int N, E;
// (to, weight)
vector<vector<pair<int, int>>> graph;
// Return: depart부터 arrival 까지 최단경로
int dijkstra(int depart, int arrival);
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> N >> E;
graph.assign(N+1, vector<pair<int, int>>());
for(int i = 0; i < E; i++){
int src, dst, w;
cin >> src >> dst >> w;
graph[src].push_back({dst, w});
graph[dst].push_back({src, w});
}
// 경유 지점
int stop1, stop2;
cin >> stop1 >> stop2;
// 경우의 수는 1->stop1->stop2->N 또는 1->stop2->stop1->N
int dist_two_stop = dijkstra(stop1, stop2);
int ans = min(dijkstra(1, stop1) + dist_two_stop + dijkstra(stop2, N), dijkstra(1, stop2) + dist_two_stop + dijkstra(stop1, N));
if(ans >= INF) cout << -1;
else cout << ans;
return 0;
}
int dijkstra(int depart, int arrival){
vector<int> distance(N+1, INF);
// (거리, 노드번호)
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
distance[depart] = 0;
pq.push({0, depart});
while(!pq.empty()){
auto [cost, now] = pq.top();
pq.pop();
// 이미 더 짧은 경로 존재하면 skip
if(distance[now] < cost) continue;
for(auto [next, weight] : graph[now]){
int new_cost = cost + weight;
if(new_cost < distance[next]){
distance[next] = new_cost;
pq.push({new_cost, next});
}
}
}
return distance[arrival];
}
INF = 10^9로 설정했는데,INF = 10^9 / 3 로 설정해서 여러 번 더해도 안전하도록 했다.graph[src].push_back({dst, w});graph[dst].push_back({src, w});이 문제에서는 시간 제한이 엄청 빡빡하지는 않아 다익스트라 5번 호출을 해도 문제가 없었으나, 더 타이트한 조건이라면 위와 같이 최적화할 수 있다.