poj 2485 Highways

答案就是最小生成树中权值最大的边

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

const int maxn=505;
struct Edge
{
    int from,to,w;
} edge[250000+10];
int n,ans;
int G[maxn][maxn];
int Father[maxn];
bool cmp(const Edge&a,const Edge&b)
{
    return a.w<b.w;
}
int Find(int x)
{
    if(x!=Father[x]) return Father[x]=Find(Father[x]);
    return Father[x];
}

int main()
{
    int T,j,i;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);

        for(i=0; i<=n; i++) Father[i]=i;
        int tot=0;

        for(i=1; i<=n; i++)
            for(j=1; j<=n; j++)
                scanf("%d",&G[i][j]);

        for(i=1; i<=n; i++)
            for(j=1; j<=n; j++)
                if(G[i][j]!=0)
                {
                    edge[tot].from=i;
                    edge[tot].to=j;
                    edge[tot].w=G[i][j];
                    tot++;
                }

        sort(edge,edge+tot,cmp);

        for(i=0; i<tot; i++)
        {
            int u=edge[i].from;
            int v=edge[i].to;
            u=Find(u);
            v=Find(v);
            if(u!=v)
            {
                Father[u]=v;
                ans=edge[i].w;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2015-08-01 10:14  Fighting_Heart  阅读(145)  评论(0编辑  收藏  举报