题解 | #畅通工程#Kruskal算法模板题,记住就行。
畅通工程
https://www.nowcoder.com/practice/23c9fe571c1346bb91fdffea8a0b195f
import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class Main { private static int[] parents; public static void main(String[] args) { Scanner sc = new Scanner(System.in); Label: while (sc.hasNextInt()) { int n = sc.nextInt(); if (n == 0) break; int m = sc.nextInt(); List<Edge> edges = new ArrayList<>(); while (n-- > 0) { int from = sc.nextInt(); int to = sc.nextInt(); int cost = sc.nextInt(); edges.add(new Edge(from, to, cost)); } edges.sort(Comparator.comparingInt(o -> o.cost)); parents = new int[m + 1]; for (int i = 1; i <= m; i++) parents[i] = i; int ans = 0; for (Edge edge : edges) { if (find(edge.from) != find(edge.to)) { parents[find(edge.from)] = find(edge.to); ans += edge.cost; } } for (int i = 1; i <= m; i++) { if (find(i) != find(1)) { System.out.println('?'); continue Label; } } System.out.println(ans); } } private static int find(int x) { return x == parents[x] ? x : (parents[x] = find(parents[x])); } private static class Edge { private final int from, to, cost; private Edge(int from, int to, int cost) { this.from = from; this.to = to; this.cost = cost; } } }