방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 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를 출력하면 된다.
5 6
1
5 1 1
1 2 2
1 3 3
2 3 4
2 4 5
3 4 6
0
2
3
7
INF
가장 기본적인 우선순위큐를 활용한 다익스트라 문제였다. 그래프 간선정보 저장을 위한 Node 와 우선순위큐에 넣을 해당 정점까지의 현재까지의 최단거리를 저장하는 PQNode 를 각각 정의하여 사용했다. 합칠 수도 있지만, 나는 이게 편하다고 느꼈다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
//그래프에 간선정보 저장위한 노드
class Node{
int n;
int dist;
Node(int n, int dist){
this.n = n;
this.dist = dist;
}
}
// 우선 순위 큐에 정점별 누적 거리 담는 노드
class PQNode implements Comparable<PQNode>{
int n;
int sum_dist;
@Override
public int compareTo(PQNode o) {
// TODO Auto-generated method stub
return this.sum_dist - o.sum_dist;
}
PQNode(int n, int sum_dist){
this.n = n;
this.sum_dist = sum_dist;
}
}
class Main
{
static int V;
static int E;
static int K;
static ArrayList<Node>[] g;
static int[] dist;
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
V = Integer.parseInt(st.nextToken()); // 정점의 개수
E = Integer.parseInt(st.nextToken()); // 간선의 개수
K = Integer.parseInt(br.readLine()); // 시작 정점의 번호
// 그래프 배열 초기화
g = new ArrayList[V+1];
for(int i = 1; i <= V; i++) g[i] = new ArrayList<>();
// 시작정점으로부터의 거리 초기화
dist = new int[V+1];
for(int i = 1; i <= V; i++) dist[i] = Integer.MAX_VALUE;
// 그래프 정보 입력 받기
for(int i = 0; i < E; i++) {
st = new StringTokenizer(br.readLine());
int fn = Integer.parseInt(st.nextToken());
int sn = Integer.parseInt(st.nextToken());
int dist = Integer.parseInt(st.nextToken());
// 방향 존재함에 유의
g[fn].add(new Node(sn, dist));
}
// 다익스트라 탐색
dijkstra(K);
// 정답 출력
for(int i = 1; i <= V; i++) {
if(dist[i] == Integer.MAX_VALUE) {
System.out.println("INF");
}
else System.out.println(dist[i]);
}
}
static void dijkstra(int st) {
PriorityQueue<PQNode> pq = new PriorityQueue<>();
// 시작점 PQ 삽입 및 최단거리에 등록
pq.offer(new PQNode(st, 0));
dist[st] = 0;
// 다익스트라 탐색 시작
while(!pq.isEmpty()) {
PQNode npq = pq.poll();
if(npq.sum_dist > dist[npq.n]) continue;
for(Node nn: g[npq.n]) {
int caledDist = npq.sum_dist + nn.dist;
// 기존의 최단거리 값이 더 작은 경우 -> PASS
if(dist[nn.n] < caledDist) continue;
// PQ에 해당 인접 노드에 대한 새로운 정보 기록 및 PQ 삽입
dist[nn.n] = caledDist;
pq.add(new PQNode(nn.n, caledDist));
}
}
}
}