zoukankan      html  css  js  c++  java
  • Kruskal

    并查集思想

    用最短边,连通(有的是间接连通)所有点;

    #include<iostream>
    #include<cstdio>
    #include<string>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    #include<queue>
    #include<math.h>
    using namespace std;
    struct    point{
        int stren;
        int x;
        int y;
    }a[120];
    int f[120];
    int n,ans=0;
    int com(const point & x,const point & y)
    {
        return x.stren<y.stren;
    }
    int father(int x)
    {
        if(f[x]!=x)    f[x]=father(f[x]);
        return f[x];
    }
    int main()
    {
        freopen("agrinet.in","r",stdin);freopen("agrinet.out","w",stdout);
        scanf("%d",&n);
        int c,cnt=0,cntt=0;
        for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
        {
            scanf("%d",&c);
            a[++cnt].x=i;a[cnt].y=j;a[cnt].stren=c;
        }
        sort(a+1,a+cnt+1,com);
        for(int i=1;i<=n;i++)    f[i]=i;
        for(int i=1;i<=cnt;i++)
        {
                if(father(a[i].x)!=father(a[i].y)) 
            {
                int x,y,stren;
                x=a[i].x;y=a[i].y;stren=a[i].stren;
                ans+=stren;
                f[father(y)]=x;
                cntt++;
            }
            if(cntt==n)    break;
        }
        cout<<ans;         
        return 0;
    }
  • 相关阅读:
    NYOJ-301递推求值
    二叉树
    从c到c++
    NYOJ-93汉诺塔(三)
    历届试题 最大子阵
    最大子序列和最大子矩阵
    【贪心】电视节目安排
    【贪心】线段覆盖
    【贪心】取数游戏
    【贪心】智力大冲浪
  • 原文地址:https://www.cnblogs.com/CLGYPYJ/p/6385238.html
Copyright © 2011-2022 走看看