https://www.acmicpc.net/problem/1753
하나의 시작점에서 다른 모든 정점까지의 최단 경로를 구해야 하며, 간선에 가중치가 있으므로 다익스트라 알고리즘으로 풀었다.
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
const int INF = 3e5;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int V, E, K;
cin >> V >> E >> K;
vector<vector<pi>> graph(V+1);
for(int i=0; i<E; i++) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back({v, w});
}
// 시작점부터 각 정점까지 최단 거리
vector<int> dist(V+1, INF);
dist[K] = 0;
// {시작점으로부터의 거리, 정점} 쌍을 min heap에 저장
priority_queue<pi, vector<pi>, greater<>> pq;
pq.push({0, K});
while(!pq.empty()) {
auto [w, v] = pq.top();
pq.pop();
// dist[v]가 더 짧은 거리로 갱신되기 전 priority queue에 삽입된 것으로, 탐색할 필요 없음
if(dist[v] < w) continue;
for(int i=0; i<graph[v].size(); i++) {
// 정점 v에 연결된 새로운 정점 nv
// 정점 v에서 정점 nv로의 간선 가중치 nw
auto [nv, nw] = graph[v][i];
nw += w;
if(nw < dist[nv]) {
dist[nv] = nw;
pq.push({nw, nv});
}
}
}
for(int i=1; i<=V; i++) {
if(dist[i] == INF) cout << "INF\n";
else cout << dist[i] << "\n";
}
return 0;
}