• [算法] kruskal最小生成树算法


    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX 100
    
    int N, M;
    
    struct Edge {
        int u,v;
        int weight;    
    } edge[MAX];
    
    int vertexs[MAX];
    int parents[MAX];
    
    int edge_cmp(const void* a, const void* b) {
        return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;  
    }
    
    int parents_find(int x) {
        int s;    
        for(s = x; parents[s] >= 0; s = parents[s]){
            ;     
        }
        return s;
    }
    
    void parents_union(int r1, int r2) {
        int s1, s2;
        int tmp;
        s1 = parents_find(r1);
        s2 = parents_find(r2);      
        tmp = parents[s1] + parents[s2];
        if(parents[s1] < parents[s2]) {
            parents[s2] = s1;     
            parents[s1] = tmp;
        }
        else {
            parents[s1] = s2;
            parents[s2] = tmp;     
        }
    }
    
    void kruskal() {
        int sum_weight = 0;
        int num = 0;
        int i, u, v;
        for(i = 0; i < M; i++) {
            u = edge[i].u;
            v = edge[i].v;
            if(parents_find(u) != parents_find(v)) {
                printf("%d %d %d
    ", u + 1, v + 1, edge[i].weight);
                num ++;
                sum_weight += edge[i].weight;     
                parents_union(parents_find(u), parents_find(v));
            }
            if(num == N -1) {
                break;     
            }
        }
        printf("weight of MST is %d
    ", sum_weight);
    }
    
    int main() {
        int i;
        int u, v, w;
         
        while(1) {
            scanf("%d%d", &N, &M);
            if(N == 0 && M == 0) {
                break;     
            } 
            /* init */
            for(i = 0; i < N; i++) {
                vertexs[i] = i;    
                parents[i] = -1;
            }
    
            for(i = 0; i < M; i++) {
                scanf("%d%d%d", &u, &v, &w);      
                u --;
                v --;
                edge[i].u = u;
                edge[i].v = v;
                edge[i].weight = w;
            }
            
            /* sort */
            qsort(edge, M, sizeof(edge[0]), edge_cmp);
            kruskal();
        } 
    
        return 0;
    }
    

    加边,并查集

  • 相关阅读:
    智能手表如何救人一命?
    人工智能、机器学习和认知计算入门指南
    PO VO BO DTO POJO DAO的解释
    web UI框架推荐
    面向切面编程AOP
    阿里巴巴java开发规范
    如何理解Spring IOC
    HTML5 3D旋转图片相册
    JSON总结笔记
    轮播图---可以动态添加图片,(封装成一个函数)
  • 原文地址:https://www.cnblogs.com/igloo1986/p/3510945.html
Copyright © 2020-2023  润新知