문제
N개의 도시와 M개의 버스가 있을 때, 출발 도시에서 도착 도시까지의 최소 비용을 구하는 문제다.
핵심 아이디어
- 양의 가중치 그래프에서 최단 경로를 구하는 Dijkstra 알고리즘을 사용한다.
priority_queue에 (거리, 노드) 쌍을 넣되, 최소 힙이 필요하므로 거리를 음수로 넣는다.- 이미 확정된 거리보다 큰 값이 큐에서 나오면 스킵한다.
풀이
#define INF 987654321
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int start, dest;
int n, m;
vector<pair<int, int>> city[1001];
int dijkstra() {
int dist[1001];
for (int i = 0; i <= n; i++) dist[i] = INT32_MAX;
priority_queue<pair<int, int>> pq;
dist[start] = 0;
pq.push({0, start});
while (!pq.empty()) {
int current = pq.top().second;
int current_distance = -pq.top().first;
pq.pop();
if (dist[current] < current_distance) continue;
for (int i = 0; i < city[current].size(); i++) {
int next = city[current][i].second;
int next_distance = current_distance + city[current][i].first;
if (dist[next] > next_distance) {
dist[next] = next_distance;
pq.push({-next_distance, next});
}
}
}
return dist[dest];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int d;
cin >> start >> dest >> d;
city[start].push_back({d, dest});
}
cin >> start >> dest;
cout << dijkstra() << endl;
return 0;
}
주요 포인트
- C++
priority_queue는 기본적으로 최대 힙이므로, 거리를 음수로 넣어 최소 힙처럼 사용한다. dist[current] < current_distance조건으로 이미 처리된 노드를 빠르게 스킵한다.- 같은 출발·도착 도시 사이에 여러 버스가 있을 수 있으므로 인접 리스트를 사용한다.
복잡도
- 시간: O((V + E) log V) — V: 도시 수, E: 버스 수
- 공간: O(V + E)
Dijkstra는 양의 가중치 그래프 최단 경로의 정석이다.
댓글