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

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1429|回复: 2
收起左侧

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

[复制链接]
QingYi. 发表于 2021-1-4 09:13


[Java] 纯文本查看 复制代码
public class Main {
    static int INF = 0x3f3f3f3f;
    static int N = 510;
    static int n,m;
    static int [][] g = new int[N][N];
    static int [] dist = new int[N];
    static boolean [] st = new boolean[N];

    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]);
        //init
        for(int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                g[i][j] = INF;
            }
        }
        while (m-- > 0){
            String[] res = bf.readLine().split(" ");
            int a = Integer.parseInt(res[0]);
            int b = Integer.parseInt(res[1]);
            int c = Integer.parseInt(res[2]);
            //无向图 两边都可以指向,且重边,选最小值
            g[a][b] = g[b][a] = Math.min(g[a][b],c);
        }
        int t = prim();
        if (t==INF){
            System.out.println("impossible");
        }else {
            System.out.println(t);
        }
    }

    private static int prim() {
        //init
        Arrays.fill(dist,INF);
        int res = 0;
        //下面这部分和Dijkstra很相似
        for (int i = 0; i < n; i++) {
            int t = -1;
            for(int j = 1;j<=n;j++){
                if (!st[j] && (t==-1 || dist[t]>dist[j])){
                    t=j;
                }
            }
            //找不到 无连通,直接return
            if (i!=0 && dist[t]==INF){
                return INF;
            }
            //否则就累加距离
            if (i!=0){
                res+=dist[t];
            }
            //更新
            //注意这里和Dijkstra的不同,一个是起点需要加上dist[t]
            //一个是集合,直接g[t][j]
            for(int j = 1;j<=n;j++){
                dist[j] = Math.min(dist[j],g[t][j]);
            }
            //当前的点设置为用过了
            st[t] = true;
        }
        return res;
    }
}

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
swz7852151 + 1 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!

查看全部评分

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

w1100312 发表于 2021-1-4 09:50
沙发。。。。。。。。。。。。。。。。。。。。。。。。。
一人之下123456 发表于 2021-1-4 11:20
您需要登录后才可以回帖 登录 | 注册[Register]

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

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

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

GMT+8, 2024-5-10 16:52

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

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