March 22, 2021
https://www.acmicpc.net/problem/1916
문제
N개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 M개의 버스가 있다. 우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다. A번째 도시에서 B번째 도시까지 가는데 드는 최소비용을 출력하여라. 도시의 번호는 1부터 N까지이다.
입력
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스의 출발 도시의 번호가 주어진다. 그리고 그 다음에는 도착지의 도시 번호가 주어지고 또 그 버스 비용이 주어진다. 버스 비용은 0보다 크거나 같고, 100,000보다 작은 정수이다.
그리고 M+3째 줄에는 우리가 구하고자 하는 구간 출발점의 도시번호와 도착점의 도시번호가 주어진다. 출발점에서 도착점을 갈 수 있는 경우만 입력으로 주어진다.
출력
첫째 줄에 출발 도시에서 도착 도시까지 가는데 드는 최소 비용을 출력한다.
다익스트라를 연습하기 위해 푼 문제이다. 아직은 잘 정리가 안되고 익숙하지 않아서 알고리즘의 수도코드를 보면서 풀었다.
다익스트라는 음수간선이 없는 경우에 효율적으로 최소신장트리를 만들 수 있는 방법이다. 우선순위 큐를 사용하면 O(ElogE) 의 시간복잡도를 가진다. 다익스트라 알고리즘은 아래와 같은 과정을 통해 최소신장트리를 생성한다.
#include <iostream>
#include <vector>
#include <climits>
#include <queue>
using namespace std;
int dist[1001];
bool visited[1001];
vector<vector<pair<int, int>>> cities(1001);
struct Compare {
bool operator()(pair<int, int>& a, pair<int, int>& b) {
return a.second > b.second;
}
};
int dijkstra(int start, int dest) {
priority_queue<pair<int, int>, vector<pair<int, int>>, Compare> pq;
pq.push({ start, 0 });
dist[start] = 0;
while (!pq.empty()) {
int costHere = pq.top().second;
int here = pq.top().first;
pq.pop();
if (dist[here] < costHere) continue;
for (auto next : cities[here]) {
int costThere = costHere + next.second;
int there = next.first;
if (costThere < dist[there]) {
dist[there] = costThere;
pq.push({ there, costThere });
}
}
}
return dist[dest];
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int N, M;
cin >> N >> M;
for (int i = 1; i <= N; i++) {
dist[i] = INT_MAX;
}
for (int i = 0; i < M; i++) {
int here, there, cost;
cin >> here >> there >> cost;
cities[here].push_back({ there, cost });
}
int start, dest;
cin >> start >> dest;
cout << dijkstra(start, dest) << endl;
}