문제
방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.
입력
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1≤K≤V)가 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 각 간선을 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u에서 v로 가는 가중치 w인 간선이 존재한다는 뜻이다. u와 v는 서로 다르며 w는 10 이하의 자연수이다. 서로 다른 두 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다.
출력
첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다.
여러 가지 시도를 해서 성공. 정렬하는 데서 이것저것 해 보다가 priority_queue를 발견하는데 시간이 좀 걸렸고,
자료형을 결정하는데 있어, pair를 쓸지, map을 쓸지, vector를 쓸지 결정하는 데도 시간이 걸렸다.
기본적인 예제이긴 하지만 연습으로 나쁘지 않았던 듯.
기본적인 다익스트라(Dijkstra) 알고리즘으로 해결.
추가로, 처음엔 막연히 adjacency matrix로 구현하려 했으나 공간이 너무 많이 필요하여 adjacency list로 변경.
#include<iostream> #include<queue> #include<map> const int LENGTH_MAX = 200010; using namespace std; int main(){ ////////////////// inputs, Initialize /////////////// int v, e, start, from, to, length; cin >> v >> e; cin >> start; priority_queue<pair<int, int>,vector<pair<int,int>>,greater<pair<int,int>>> q; // save distance(result) in order of <distance, vertex> int dist[v]; map<int, int> edge[v]; // adjacency list bool done[v]; for(int i = 0; i < v; i++){ dist[i] = LENGTH_MAX; done[i] = false; } dist[start-1] = 0; q.push(make_pair(0,start-1)); for(int i = 0; i < e; i++){ cin >> from >> to >> length; if( edge[from-1][to-1] == 0 || length < edge[from-1][to-1] ) edge[from-1][to-1] = length; } /////////////////////// body part ///////////////////////// while(!q.empty()){ int cur_vert = q.top().second; int cur_dist = q.top().first; q.pop(); if(done[cur_vert]) continue; done[cur_vert] = true; for(pair<const int, int> temp : edge[cur_vert]){ // temp.first : vertex index , temp.second : edge length if( temp.second + cur_dist < dist[temp.first] ){ dist[temp.first] = temp.second + cur_dist; q.push(make_pair(dist[temp.first], temp.first)); } } } ///////////////////// print results /////////////////////// for(int i = 0; i < v; i++){ if(dist[i] == LENGTH_MAX){ cout << "INF"; } else { cout << dist[i]; } cout << '\n'; } return 0; }