Skip to content

Commit 0d1289d

Browse files
authored
Merge pull request #812 from AlgorithmWithGod/LiiNi-coder
[20250903] BOJ / G5 / 최소비용 구하기 / 이인희
2 parents 3391873 + d843ff1 commit 0d1289d

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.ArrayList;
6+
import java.util.Arrays;
7+
import java.util.List;
8+
import java.util.PriorityQueue;
9+
import java.util.StringTokenizer;
10+
11+
public class Main {
12+
private static BufferedReader br;
13+
private static int n;
14+
private static int m;
15+
private static List<Node>[] graph;
16+
private static int[] dist;
17+
18+
private static class Node implements Comparable<Node> {
19+
int v;
20+
int w;
21+
public Node(int v, int w) {
22+
this.v = v;
23+
this.w = w;
24+
}
25+
@Override
26+
public int compareTo(Node other) {
27+
return this.w - other.w;
28+
}
29+
}
30+
31+
public static void main(String[] args) throws IOException {
32+
br = new BufferedReader(new InputStreamReader(System.in));
33+
n = Integer.parseInt(br.readLine());
34+
m = Integer.parseInt(br.readLine());
35+
graph = new ArrayList[n + 1];
36+
for (int i = 1; i <= n; i++) {
37+
graph[i] = new ArrayList<>();
38+
}
39+
for (int i = 0; i < m; i++) {
40+
StringTokenizer st = new StringTokenizer(br.readLine());
41+
int a = Integer.parseInt(st.nextToken());
42+
int b = Integer.parseInt(st.nextToken());
43+
int c = Integer.parseInt(st.nextToken());
44+
45+
graph[a].add(new Node(b, c));
46+
}
47+
StringTokenizer st = new StringTokenizer(br.readLine());
48+
int start = Integer.parseInt(st.nextToken());
49+
int end = Integer.parseInt(st.nextToken());
50+
dist = new int[n + 1];
51+
Arrays.fill(dist, Integer.MAX_VALUE);
52+
53+
dijkstra(start);
54+
55+
System.out.println(dist[end]);
56+
}
57+
58+
private static void dijkstra(int start) {
59+
PriorityQueue<Node> pq = new PriorityQueue<>();
60+
dist[start] = 0;
61+
pq.add(new Node(start, 0));
62+
while (!pq.isEmpty()) {
63+
Node now = pq.poll();
64+
if (dist[now.v] < now.w) continue;
65+
for (Node next : graph[now.v]) {
66+
if (dist[next.v] > dist[now.v] + next.w) {
67+
dist[next.v] = dist[now.v] + next.w;
68+
pq.add(new Node(next.v, dist[next.v]));
69+
}
70+
}
71+
}
72+
}
73+
}
74+
```

0 commit comments

Comments
 (0)