吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1283|回复: 0
收起左侧

[Java 转载] 【笔记】数据结构与算法之最小生成树(Kruskal算法)

[复制链接]
QingYi. 发表于 2021-1-5 09:34
[Java] 纯文本查看 复制代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    static class Edge{
        int a,b,w;
        public Edge(int a,int b, int w){
            this.a = a;
            this.b = b;
            this.w = w;
        }
    }
    static int n,m;
    //总的边
    static int cnt = 0;
    static Edge[] edges;
    static int [] p;

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String[] s = bf.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        m = Integer.parseInt(s[1]);
        edges = new Edge[m];
        p = new int[n+1];
        for(int i =1 ;i<=n;i++){
            p[i] = i;
        }
        for(int i = 0; i < m; i++){
            String[] res = bf.readLine().split(" ");
            int x = Integer.parseInt(res[0]);
            int y = Integer.parseInt(res[1]);
            int w = Integer.parseInt(res[2]);
            edges[i] = new Edge(x,y,w);
        }
        //权重从小到大排序
        Arrays.sort(edges,(a,b) -> a.w - b.w);
        //最小生成树权重之和
        int res =0;
        for (int i = 0; i < m; i++) {
            Edge e = edges[i];
            int x = find(e.a);
            int y = find(e.b);
            if (x!=y){
                res+=e.w;
                p[x] =y;
                cnt++;
            }
        }
        if(cnt<n-1){
            System.out.println("failed");
        }else {
            System.out.println(res);
        }
    }
    public static int find(int x){
        if (p[x] !=x){
            p[x] = find(p[x]);
        }
        return p[x];
    }
}

在新标签打开所有链接复制所有链接URL复制所有链接URL(反向)复制所有链接标题 + URL复制所有链接标题 + URL (MD)复制所有链接标题 + URL (BBS)复制所有链接标题 + URL (筛选)复制所有链接标题 + URL (设置复制格式)在新标签页打开所有图片链接在一个标签页显示所有图片链接
复选框 - 选中
复选框 - 取消
复选框 - 反选
单选框 - 选中
单选框 - 取消
特殊单选框 - 选中

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-10 06:08

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表