Kruscal算法1.3

http://poj.org/problem?id=2485

给定一个图中的关系矩阵,求连接全部点中需要最大边的最小值

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define maxn 102
#define INF 1000000
using namespace std;
struct node
{
    int u;
    int v;
    int w;
    node()
    {
        w=1000000;
    }
} edge[500000];
int pre[10000];
int n,m;
bool cmp(const node&a,const node&b )
{
    return a.w<b.w;
}
int find(int x)
{
    return x==pre[x]?x:pre[x]=find(pre[x]);
}
void unions(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
    {
        pre[fx]=fy;
    }
}
void createGraph()
{
    for(int i=1; i<=n; i++)pre[i]=i;
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
        {
            int u,v,w;
            scanf("%d",&w);
            if(i!=j)
            {
                edge[++m].u=i;
                edge[m].v=j;
                edge[m].w=w;
            }
        }
    }

}
int kruscal()
{
    int ans=0,ans1=-1;
    sort(edge+1,edge+m+1,cmp);
    for(int i=1; i<=m; i++)
    {
        if(find(edge[i].u)!=find(edge[i].v))
        {
            unions(edge[i].u,edge[i].v);
            ans+=edge[i].w;
            ans1=max(ans1,edge[i].w);
        }
    }
    return ans1;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n;
        m=0;
        createGraph();
        cout<<kruscal()<<endl;

    }
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/83210855