Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions JHLEE325/202507/31 BOJ G3 최소비용 구하기 2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
```java
import java.io.*;
import java.util.*;

public class Main {

static class Node implements Comparable<Node> {
int dest, cost;
Node(int dest, int cost) {
this.dest = dest;
this.cost = cost;
}

@Override
public int compareTo(Node o) {
return this.cost - o.cost;
}
}

static int n, m, start, destination;
static List<List<Node>> graph = new ArrayList<>();

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;

n = Integer.parseInt(br.readLine());
m = Integer.parseInt(br.readLine());

for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}

for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
graph.get(s).add(new Node(d, c));
}

st = new StringTokenizer(br.readLine());
start = Integer.parseInt(st.nextToken());
destination = Integer.parseInt(st.nextToken());

dijkstra(start, destination);
}

static void dijkstra(int start, int end) {
int[] dist = new int[n + 1];
int[] prev = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
Arrays.fill(prev, -1);

PriorityQueue<Node> pq = new PriorityQueue<>();
dist[start] = 0;
pq.add(new Node(start, 0));

while (!pq.isEmpty()) {
Node cur = pq.poll();

if (dist[cur.dest] < cur.cost) continue;

for (Node next : graph.get(cur.dest)) {
if (dist[next.dest] > dist[cur.dest] + next.cost) {
dist[next.dest] = dist[cur.dest] + next.cost;
prev[next.dest] = cur.dest;
pq.add(new Node(next.dest, dist[next.dest]));
}
}
}

List<Integer> path = new ArrayList<>();
int cur = end;
while (cur != -1) {
path.add(cur);
cur = prev[cur];
}
Collections.reverse(path);

System.out.println(dist[end]);
System.out.println(path.size());
for (int p : path) {
System.out.print(p + " ");
}
}
}

```