Constructing Roads----poj2421(最小生成树Kruskal)

题目链接:

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

想把n个村庄连接在一起;求最小生成树,不同的是已经有了m条线段链接在一起了,求剩下的;

感觉用Kruskal会简单一点

#include<stdio.h>
#include<string.h>
#include<map>
#include<iostream>
#include<algorithm>
#include<math.h>
#define N 110
#define INF 0xfffffff

using namespace std;

int f[N];

struct node
{
    int x,y,d;
}a[N*N];

int cmp(node p,node q)
{
    return p.d < q.d;
}

int Find(int x)
{
    if(x!=f[x])
        f[x]=Find(f[x]);
    return f[x];
}

int main()
{
    int n, i, j, k, m, d, x, y, px, py, ans;
    while(scanf("%d",&n)!=EOF)
    {
        memset(a, 0, sizeof(a));
        k = ans = 0;
        for(i=0;i<=n;i++)
            f[i]=i;
        for(i=1; i<=n; i++)
            for(j=1; j<=n; j++)
            {
                scanf("%d",&d);
                if(i<j)
                    a[k].x = i, a[k].y = j, a[k++].d = d;
            }
        sort(a,a+k,cmp);
        scanf("%d", &m);
        for(i=0; i<m; i++)
        {
            scanf("%d%d", &x, &y);
            px = Find(x);
            py = Find(y);
            if(px != py)
                f[px] = py;
        }
        for(i=0; i<k; i++)
        {
            px = Find(a[i].x);
            py = Find(a[i].y);
            if(px != py)
                f[px] = py,ans+=a[i].d;
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2015-07-27 16:14  西瓜不懂柠檬的酸  Views(133)  Comments(0Edit  收藏  举报
levels of contents