最小生成树

 

一道简单的最小生成树

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int n,a[105][105],f[105],cnt,ans;

struct city
{
    int x,y,z;
}e[10005];

bool mza(const city &f1,const city &f2)
{
    return f1.z<f2.z;
}

int gets(int o)
{
    if(f[o]==o) return o;
    else
    {
        f[o]=gets(f[o]);
        return f[o];
    }
}

bool wht(int r,int w)
{
    int t1=gets(r),t2=gets(w);
    if(t1!=t2)
    {
        f[t2]=t1;
        return 1;
    }
    return 0;
}
int main()
{
    int i,j,k=0;
    cin>>n;
    for(i=1;i<=n;i++)
    {
        f[i]=i;
        for(j=1;j<=n;j++)
        {
            scanf("%d",&a[i][j]);
            if(i<j)
            {
                e[k].x=i;
                e[k].y=j;
                e[k++].z=a[i][j];
            }
        }
    }
    sort(e,e+k,mza);
    /*
    for(i=0;i<k;i++)
        cout<<e[i].x<<" "<<e[i].y<<" "<<e[i].z<<endl;
    */
    for(i=0;i<k;i++)
    {
        if(wht(e[i].x,e[i].y))
        {
            cnt++;
            ans+=e[i].z;
        }
        if(cnt==n-1) break;
    }
    printf("%d",ans);
    return 0;
}
View Code

 

posted @ 2017-07-20 15:57  白驹过隙----青春绿  Views(162)  Comments(1Edit  收藏  举报