diff --git "a/JHLEE325/202507/31 BOJ G3 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260 2.md" "b/JHLEE325/202507/31 BOJ G3 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260 2.md" new file mode 100644 index 00000000..a29f6f91 --- /dev/null +++ "b/JHLEE325/202507/31 BOJ G3 \354\265\234\354\206\214\353\271\204\354\232\251 \352\265\254\355\225\230\352\270\260 2.md" @@ -0,0 +1,89 @@ +```java +import java.io.*; +import java.util.*; + +public class Main { + + static class Node implements Comparable { + 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> 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 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 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 + " "); + } + } +} + +```