Skip to content

Commit 32b42b3

Browse files
authored
Merge pull request #1073 from AlgorithmWithGod/Ukj0ng
[20251009] BOJ / P4 / K번째 최단경로 찾기 / 한종욱
2 parents d92b050 + 13b12e9 commit 32b42b3

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
```
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
private static PriorityQueue<Long>[] dist;
9+
private static List<Node>[] graph;
10+
private static int n, m, k;
11+
12+
public static void main(String[] args) throws IOException {
13+
init();
14+
dijkstra();
15+
16+
for (int i = 1; i <= n; i++) {
17+
if (dist[i].size() < k) {
18+
bw.write("-1" + "\n");
19+
} else {
20+
bw.write(dist[i].peek() + "\n");
21+
}
22+
}
23+
bw.flush();
24+
bw.close();
25+
br.close();
26+
}
27+
28+
private static void init() throws IOException {
29+
StringTokenizer st = new StringTokenizer(br.readLine());
30+
n = Integer.parseInt(st.nextToken());
31+
m = Integer.parseInt(st.nextToken());
32+
k = Integer.parseInt(st.nextToken());
33+
34+
dist = new PriorityQueue[n+1];
35+
graph = new List[n+1];
36+
37+
for (int i = 0; i <= n; i++) {
38+
dist[i] = new PriorityQueue<>((o1, o2) -> Long.compare(o2, o1));
39+
graph[i] = new ArrayList<>();
40+
}
41+
42+
for (int i = 0; i < m; i++) {
43+
st = new StringTokenizer(br.readLine());
44+
int a = Integer.parseInt(st.nextToken());
45+
int b = Integer.parseInt(st.nextToken());
46+
long c = Long.parseLong(st.nextToken());
47+
48+
graph[a].add(new Node(b, c));
49+
}
50+
}
51+
52+
private static void dijkstra() {
53+
PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> Long.compare(o1.cost, o2.cost));
54+
dist[1].add(0L);
55+
pq.add(new Node(1, 0L));
56+
57+
while (!pq.isEmpty()) {
58+
Node current = pq.poll();
59+
60+
for (Node next : graph[current.dest]) {
61+
long nCost = current.cost + next.cost;
62+
if (dist[next.dest].size() < k) {
63+
dist[next.dest].add(nCost);
64+
pq.add(new Node(next.dest, nCost));
65+
} else if (dist[next.dest].peek() > nCost) {
66+
dist[next.dest].poll();
67+
dist[next.dest].add(nCost);
68+
pq.add(new Node(next.dest, nCost));
69+
}
70+
}
71+
}
72+
}
73+
74+
static class Node {
75+
int dest;
76+
long cost;
77+
78+
Node (int dest, long cost) {
79+
this.dest = dest;
80+
this.cost = cost;
81+
}
82+
}
83+
}
84+
```

0 commit comments

Comments
 (0)