|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +class Main { |
| 5 | + |
| 6 | + static int n, m; |
| 7 | + static List<int[]>[] graph; |
| 8 | + static List<int[]> edges = new ArrayList<>(); |
| 9 | + |
| 10 | + public static void main(String[] args) throws Exception { |
| 11 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 13 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 14 | + n = Integer.parseInt(st.nextToken()); |
| 15 | + m = Integer.parseInt(st.nextToken()); |
| 16 | + graph = new ArrayList[n + 1]; |
| 17 | + |
| 18 | + for (int i = 0; i <= n; i++) { |
| 19 | + graph[i] = new ArrayList<>(); |
| 20 | + } |
| 21 | + |
| 22 | + for (int i = 0; i < m; i++) { |
| 23 | + st = new StringTokenizer(br.readLine()); |
| 24 | + int a = Integer.parseInt(st.nextToken()); |
| 25 | + int b = Integer.parseInt(st.nextToken()); |
| 26 | + int c = Integer.parseInt(st.nextToken()); |
| 27 | + graph[a].add(new int[]{a, b, c}); |
| 28 | + graph[b].add(new int[]{b, a, c}); |
| 29 | + } |
| 30 | + |
| 31 | + dijkstra(); |
| 32 | + |
| 33 | + StringBuilder answer = new StringBuilder(); |
| 34 | + answer.append(edges.size()).append("\n"); |
| 35 | + for (int[] edge : edges) { |
| 36 | + answer.append(edge[0]).append(" ").append(edge[1]).append("\n"); |
| 37 | + } |
| 38 | + bw.write(answer.toString()); |
| 39 | + bw.flush(); |
| 40 | + bw.close(); |
| 41 | + } |
| 42 | + |
| 43 | + public static void dijkstra() { |
| 44 | + int[] dist = new int[n + 1]; |
| 45 | + boolean[] visited = new boolean[n + 1]; |
| 46 | + Arrays.fill(dist, 1_000_000); |
| 47 | + PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[2])); |
| 48 | + dist[1] = 0; |
| 49 | + visited[1] = true; |
| 50 | + pq.offer(new int[]{1, 1, 0}); // from, to, cost |
| 51 | + |
| 52 | + while (!pq.isEmpty()) { |
| 53 | + int[] current = pq.poll(); |
| 54 | + |
| 55 | + if (!visited[current[1]]) { |
| 56 | + visited[current[1]] = true; |
| 57 | + edges.add(current); |
| 58 | + } |
| 59 | + |
| 60 | + for (int[] next : graph[current[1]]) { |
| 61 | + if (dist[next[1]] > current[2] + next[2]) { |
| 62 | + dist[next[1]] = current[2] + next[2]; |
| 63 | + pq.offer(new int[]{current[1], next[1], dist[next[1]]}); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments