https://www.acmicpc.net/problem/1753
전형적인 다익스트라(Dijkstra) 알고리즘 문제입니다.
하나의 시작 정점에서 모든 정점까지의 최단 경로를 구하는 알고리즘
graph = new ArrayList<>();
for (int i = 0; i <= v; i++) graph.add(new ArrayList<>());
for (int i = 0; i < e; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
graph.get(u).add(new Node(v, w));
}
그래프는 인접 리스트로 구현했습니다.
dist = new int[v+1];
Arrays.fill(dist, INF);
dist[start] = 0;
그래프 구현이 끝났으면, 거리 배열을 초기화해 줍니다.
private static void dijkstra() {
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.add(new Node(start, 0));
while (!pq.isEmpty()) {
Node cur = pq.poll();
int u = cur.idx;
int d = cur.cost;
if (d > dist[u]) continue;
for (Node nxt : graph.get(u)) {
int v = nxt.idx;
int w = nxt.cost;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.add(new Node(v, dist[v]));
}
}
}
}
pq에 시작 노드와 이동 거리 0을 넣어 줍니다.u와 거리 d를 pop 해준 후 다음 노드를 비교합니다.v와 가중치 w를 꺼내 다음 노드까지의 거리 dist[v]의 값이 현재 노드의 거리 dist[u]와 가중치를 합한 값을 비교하여 최솟값을 갱신해 줍니다.pq에 해당 노드와 거리를 삽입해 줍니다.이렇게 모든 인접 노드까지의 거리를 갱신했다면, 다 출력해 주면 끝입니다 😊
import java.util.*;
import java.io.*;
public class Main {
static class Node implements Comparable<Node> {
int idx, cost;
Node (int idx, int cost) {
this.idx = idx;
this.cost = cost;
}
@Override
public int compareTo(Node o) {
return this.cost - o.cost;
}
}
static StringBuilder sb = new StringBuilder();
static final int INF = (int) 1e9;
static int v, e, start;
static List<ArrayList<Node>> graph;
static int[] dist;
private static void dijkstra() {
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.add(new Node(start, 0));
while (!pq.isEmpty()) {
Node cur = pq.poll();
int u = cur.idx;
int d = cur.cost;
if (d > dist[u]) continue;
for (Node nxt : graph.get(u)) {
int v = nxt.idx;
int w = nxt.cost;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.add(new Node(v, dist[v]));
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
v = Integer.parseInt(st.nextToken());
e = Integer.parseInt(st.nextToken());
start = Integer.parseInt(br.readLine());
graph = new ArrayList<>();
for (int i = 0; i <= v; i++) graph.add(new ArrayList<>());
for (int i = 0; i < e; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
graph.get(u).add(new Node(v, w));
}
dist = new int[v+1];
Arrays.fill(dist, INF);
dist[start] = 0;
dijkstra();
for (int i = 1; i <= v; i++) {
sb.append((dist[i] == INF) ? "INF" : dist[i]).append("\n");
}
System.out.println(sb.toString());
}
}
정말 좋은 설명이네요 많은 도움이 됐습니다!