
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
public static class Node {
int to;
int cost;
Node(int t, int c) {
this.to = t;
this.cost = c;
}
}
static BufferedReader br;
static BufferedWriter bw;
static List<List<Node>> nodeList;
static int V, E, start;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
V = Integer.parseInt(st.nextToken());
E = Integer.parseInt(st.nextToken());
start = Integer.parseInt(br.readLine());
nodeList = new ArrayList<>();
for (int i = 0; i <= V; i++) {
nodeList.add(new ArrayList<>());
}
for (int i = 0; i < E; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
nodeList.get(start).add(new Node(to, cost));
}
br.close();
int[] from = dijkstra(start, V);
for (int i = 1; i <= V; i++) {
int cost = from[i];
if (cost == Integer.MAX_VALUE) {
bw.write("INF\n");
} else {
bw.write(cost + "\n");
}
}
bw.close();
}
public static int[] dijkstra(int start, int to) {
int[] distance = new int[V + 1];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[start] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> o1.cost - o2.cost);
pq.add(new Node(start, 0));
while (!pq.isEmpty()) {
Node current = pq.poll();
if (current.cost > distance[current.to]) {
continue;
}
for (Node next : nodeList.get(current.to)) {
if (distance[next.to] > current.cost + next.cost) {
distance[next.to] = current.cost + next.cost;
pq.add(new Node(next.to, distance[next.to]));
}
}
}
return distance;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 1987번: 알파벳 (0) | 2025.05.03 |
|---|---|
| [JAVA-자바] 1967번: 트리의 지름 (0) | 2025.05.03 |
| [JAVA-자바] 1504번: 특정한 최단 경로 (0) | 2025.05.02 |
| [JAVA-자바] 1043번: 거짓말 (0) | 2025.04.30 |
| [JAVA-자바] 17070번: 파이프 옮기기 1 (0) | 2025.04.29 |