|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N; |
| 7 | + static HashMap<Integer, List<Node>> routes; |
| 8 | + static StringBuilder sb = new StringBuilder(); |
| 9 | + |
| 10 | + static class Node { |
| 11 | + int node; |
| 12 | + int dist; |
| 13 | + int route; |
| 14 | + |
| 15 | + Node(int node, int dist, int route) { |
| 16 | + this.node = node; |
| 17 | + this.dist = dist; |
| 18 | + this.route = route; |
| 19 | + } |
| 20 | + |
| 21 | + @Override |
| 22 | + public String toString() { |
| 23 | + return "{node} " + this.node + " " + this.dist + " " + this.route; |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + public static void dijkstra(int startNode) { |
| 28 | + PriorityQueue<Node> queue = new PriorityQueue<>((s, e) -> s.dist- e.dist); |
| 29 | + |
| 30 | + int[] path = new int[N+1]; |
| 31 | + path[startNode] = startNode; |
| 32 | + for(Node n : routes.getOrDefault(startNode, new ArrayList<>())) { |
| 33 | + queue.add(new Node(n.node, n.dist, n.route)); |
| 34 | + } |
| 35 | + |
| 36 | + while (!queue.isEmpty()) { |
| 37 | + Node now = queue.poll(); |
| 38 | + if (path[now.node] != 0) continue; |
| 39 | + path[now.node] = now.route; |
| 40 | + for(Node n : routes.getOrDefault(now.node, new ArrayList<>())) { |
| 41 | + if (path[n.node] == 0) { |
| 42 | + queue.add(new Node(n.node, now.dist + n.dist, now.route)); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + for(int i = 1; i <= N; i++) { |
| 48 | + if (i == startNode) sb.append("- "); |
| 49 | + else sb.append(path[i]).append(" "); |
| 50 | + } |
| 51 | + sb.append("\n"); |
| 52 | + |
| 53 | + } |
| 54 | + |
| 55 | + public static void main(String[] args) throws IOException { |
| 56 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 57 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 58 | + |
| 59 | + N = Integer.parseInt(st.nextToken()); |
| 60 | + int M = Integer.parseInt(st.nextToken()); |
| 61 | + |
| 62 | + routes = new HashMap<>(); |
| 63 | + |
| 64 | + for(int m = 0; m < M; m++) { |
| 65 | + st = new StringTokenizer(br.readLine()); |
| 66 | + int s = Integer.parseInt(st.nextToken()); |
| 67 | + int e = Integer.parseInt(st.nextToken()); |
| 68 | + int w = Integer.parseInt(st.nextToken()); |
| 69 | + |
| 70 | + if (!routes.containsKey(s)) |
| 71 | + routes.put(s, new ArrayList<>()); |
| 72 | + if (!routes.containsKey(e)) |
| 73 | + routes.put(e, new ArrayList<>()); |
| 74 | + |
| 75 | + routes.get(s).add(new Node(e, w, e)); |
| 76 | + routes.get(e).add(new Node(s, w, s)); |
| 77 | + } |
| 78 | + |
| 79 | + for(int i = 1; i <= N; i++) { |
| 80 | + dijkstra(i); |
| 81 | + } |
| 82 | + |
| 83 | + System.out.println(sb); |
| 84 | + } |
| 85 | +} |
0 commit comments