• 图论-kruskal算法-稀疏图


    #include<cstdio>
    #include<algorithm>
    using namespace std;
    const int MAXV = 1000;
    const int INF = 0xFFFFFFF;
    struct edge{
        int u,v,cost;
    }E[MAXV];
    bool cmp(edge a,edge b){ return a.cost < b.cost; }
    int father[MAXV];
    int findFather(int x)
    {
        int a = x;
        while(x != father[x]) x=father[x];
        //路径压缩
        while(a != father[a])
        {
            int temp = a;
            a = father[a];
            father[temp]=x;    
        }    
        return x;
    } 
    int kruskal(int n,int m)
    {
        int ans=0,numEdge=0;
        for(int i=0;i<n;i++) father[i]=i;
        sort(E,E+m,cmp);
        for(int i=0;i<m;i++)
        {
            int faU=findFather(E[i].u);
            int faV=findFather(E[i].v);
            if(faU!=faV)
            {
                father[faU]=faV;
                ans += E[i].cost; 
                numEdge++;
                if(numEdge==n-1) break;
            }
        }
        if(numEdge!=n-1) return -1;
        return ans;
    }
    int main(void)
    {
        int m,n;
        scanf("%d%d",&n,&m);
        for(int i=0;i<m;i++) scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].cost);
        int ans = kruskal(n,m);
        printf("%d",ans); 
        return 0;
    }
     /*
    6 10
    0 1 4
    0 4 1
    0 5 2 
    1 2 1
    1 5 3
    2 3 6
    2 5 5 
    3 4 5
    3 5 4
    4 5 3
    output:
    11
     */
  • 相关阅读:
    POJ 2752 Seek the Name, Seek the Fame
    POJ 2406 Power Strings
    KMP 算法总结
    SGU 275 To xor or not to xor
    hihocoder 1196 高斯消元.二
    hihoCoder 1195 高斯消元.一
    UvaLive 5026 Building Roads
    HDU 2196 computer
    Notions of Flow Networks and Flows
    C/C++代码中的笔误
  • 原文地址:https://www.cnblogs.com/zuimeiyujianni/p/8848677.html
Copyright © 2020-2023  润新知