Skip to content

Commit d4dd980

Browse files
authored
Merge pull request #580 from AlgorithmWithGod/JHLEE325
[20250731] BOJ / G3 / 최소비용 구하기 2 / 이준희
2 parents d78f340 + 490ff7a commit d4dd980

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static class Node implements Comparable<Node> {
8+
int dest, cost;
9+
Node(int dest, int cost) {
10+
this.dest = dest;
11+
this.cost = cost;
12+
}
13+
14+
@Override
15+
public int compareTo(Node o) {
16+
return this.cost - o.cost;
17+
}
18+
}
19+
20+
static int n, m, start, destination;
21+
static List<List<Node>> graph = new ArrayList<>();
22+
23+
public static void main(String[] args) throws Exception {
24+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
25+
StringTokenizer st;
26+
27+
n = Integer.parseInt(br.readLine());
28+
m = Integer.parseInt(br.readLine());
29+
30+
for (int i = 0; i <= n; i++) {
31+
graph.add(new ArrayList<>());
32+
}
33+
34+
for (int i = 0; i < m; i++) {
35+
st = new StringTokenizer(br.readLine());
36+
int s = Integer.parseInt(st.nextToken());
37+
int d = Integer.parseInt(st.nextToken());
38+
int c = Integer.parseInt(st.nextToken());
39+
graph.get(s).add(new Node(d, c));
40+
}
41+
42+
st = new StringTokenizer(br.readLine());
43+
start = Integer.parseInt(st.nextToken());
44+
destination = Integer.parseInt(st.nextToken());
45+
46+
dijkstra(start, destination);
47+
}
48+
49+
static void dijkstra(int start, int end) {
50+
int[] dist = new int[n + 1];
51+
int[] prev = new int[n + 1];
52+
Arrays.fill(dist, Integer.MAX_VALUE);
53+
Arrays.fill(prev, -1);
54+
55+
PriorityQueue<Node> pq = new PriorityQueue<>();
56+
dist[start] = 0;
57+
pq.add(new Node(start, 0));
58+
59+
while (!pq.isEmpty()) {
60+
Node cur = pq.poll();
61+
62+
if (dist[cur.dest] < cur.cost) continue;
63+
64+
for (Node next : graph.get(cur.dest)) {
65+
if (dist[next.dest] > dist[cur.dest] + next.cost) {
66+
dist[next.dest] = dist[cur.dest] + next.cost;
67+
prev[next.dest] = cur.dest;
68+
pq.add(new Node(next.dest, dist[next.dest]));
69+
}
70+
}
71+
}
72+
73+
List<Integer> path = new ArrayList<>();
74+
int cur = end;
75+
while (cur != -1) {
76+
path.add(cur);
77+
cur = prev[cur];
78+
}
79+
Collections.reverse(path);
80+
81+
System.out.println(dist[end]);
82+
System.out.println(path.size());
83+
for (int p : path) {
84+
System.out.print(p + " ");
85+
}
86+
}
87+
}
88+
89+
```

0 commit comments

Comments
 (0)