题解 | #还是畅通工程#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]));
    }
}

全部评论

相关推荐

字节一直是我的白月光,考虑到转正还是拒了日常实习。
从今天开始狠狠卷JVAV_癫:为什么你释放的offer没流到我头上
点赞 评论 收藏
分享
qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-25 20:45
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务