题解 | #还是畅通工程#Kruskal模板题,记住就行。

还是畅通工程

https://www.nowcoder.com/practice/d6bd75dbb36e410995f8673a6a2e2229

import java.util.*;
public class Main {
    private static class Edge {
        private final int from, to, val;
        private Edge(int from, int to, int val) {
            this.from = from;
            this.to = to;
            this.val = val;
        }
    }
    private static int[] parents;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            int n = sc.nextInt();
            if (n == 0) break;
            parents = new int[n + 1];
            for (int i = 1; i <= n; i++) parents[i] = i;
            List<Edge> edges = new ArrayList<>();
            for (int i = 0; i < n * (n - 1) / 2; i++) {
                int from = sc.nextInt();
                int to = sc.nextInt();
                int val = sc.nextInt();
                edges.add(new Edge(from, to, val));
            }
            edges.sort(Comparator.comparingInt(edge -> edge.val));
            int ans = 0;
            for (Edge edge : edges) {
                int x = find(edge.from);
                int y = find(edge.to);
                if (x != y) {
                    parents[x] = y;
                    ans += edge.val;
                }
            }
            System.out.println(ans);
        }
    }
    private static int find(int x) {
        return x == parents[x] ? x : (parents[x] = find(parents[x]));
    }
}

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务