Skip to content

Commit ce970b4

Browse files
committed
[20260104] BOJ / G5 / 간선 이어가기 2 / 김민진
1 parent 7ba3183 commit ce970b4

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class BJ_14284_간선_이어가기_2 {
6+
7+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
9+
private static StringTokenizer st;
10+
11+
private static int N, M, S, T;
12+
private static int[] dist;
13+
private static List<Node>[] graph;
14+
private static Queue<Node> q;
15+
16+
private static class Node implements Comparable<Node> {
17+
int to;
18+
int weight;
19+
20+
public Node(int to, int weight) {
21+
this.to = to;
22+
this.weight = weight;
23+
}
24+
25+
@Override
26+
public int compareTo(Node o) {
27+
return Integer.compare(this.weight, o.weight);
28+
}
29+
30+
}
31+
32+
public static void main(String[] args) throws IOException {
33+
init();
34+
sol();
35+
36+
bw.flush();
37+
bw.close();
38+
br.close();
39+
}
40+
41+
private static void init() throws IOException {
42+
st = new StringTokenizer(br.readLine());
43+
N = Integer.parseInt(st.nextToken());
44+
M = Integer.parseInt(st.nextToken());
45+
46+
graph = new List[N + 1];
47+
for (int i = 1; i <= N; i++) {
48+
graph[i] = new ArrayList<>();
49+
}
50+
51+
for (int i = 0; i < M; i++) {
52+
st = new StringTokenizer(br.readLine());
53+
54+
int a = Integer.parseInt(st.nextToken());
55+
int b = Integer.parseInt(st.nextToken());
56+
int c = Integer.parseInt(st.nextToken());
57+
58+
graph[a].add(new Node(b, c));
59+
graph[b].add(new Node(a, c));
60+
}
61+
62+
st = new StringTokenizer(br.readLine());
63+
S = Integer.parseInt(st.nextToken());
64+
T = Integer.parseInt(st.nextToken());
65+
66+
dist = new int[N + 1];
67+
Arrays.fill(dist, 987654321);
68+
q = new PriorityQueue<>();
69+
}
70+
71+
private static void sol() throws IOException {
72+
q.offer(new Node(S, 0));
73+
dist[S] = 0;
74+
75+
while (!q.isEmpty()) {
76+
Node cur = q.poll();
77+
78+
if (dist[cur.to] < cur.weight) continue;
79+
80+
if (cur.to == T) {
81+
bw.write(cur.weight + "");
82+
return;
83+
}
84+
85+
for (Node next : graph[cur.to]) {
86+
int newDist = dist[cur.to] + next.weight;
87+
88+
if (newDist < dist[next.to]) {
89+
dist[next.to] = newDist;
90+
q.offer(new Node(next.to, newDist));
91+
}
92+
}
93+
}
94+
}
95+
96+
}
97+
```

0 commit comments

Comments
 (0)