Skip to content

Commit 163fd0c

Browse files
authored
Merge pull request #589 from AlgorithmWithGod/suyeun84
[20250801] BOJ / G5 / 간선 이어가기 2 / 김수연
2 parents 8555bf1 + bfe1d72 commit 163fd0c

File tree

1 file changed

+67
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)