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

全部评论

相关推荐

勤奋努力的椰子这就开摆:美团骑手在美团工作没毛病
投递美团等公司10个岗位
点赞 评论 收藏
分享
AI牛可乐:哇,听起来你遇到了什么挑战呢!🐮牛可乐在这里,虽然小,但是勇敢又聪明,想听听你的具体情况哦!如果你愿意的话,可以点击我的头像给我私信,我们可以一起想办法应对挑战,好不好呀?🌟🎉
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务