poj 2421 Constructing Roads 最小生成树

把已经有的边,加入到图中,再用克鲁斯卡尔算最小生成树

简单的一道题,但是我居然把输出看错意思了....

View Code
#include <stdio.h>
#include <algorithm>

using namespace std;

struct node
{
int s,e,len;
}map[5055];
int k,f[105];

int cmp(node a,node b)
{
return a.len<b.len;
}

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

int Union(int s,int e)
{
s=Find(s),e=Find(e);
if(s==e)return 0;
f[s]=f[e]=s<e?s:e;
return 1;
}

void Kul()
{
int i,ans=0;
for (i=0;i<k;i++)
{
if(Union(map[i].e,map[i].s))
{
ans+=map[i].len;
}
}
printf("%d\n",ans);
}

int main()
{
int n,i,j,a,s,e,m;
k=0;
scanf("%d",&n);
for (i=0;i<n;i++)f[i]=i;
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
{
scanf("%d",&a);
if(i>=j)continue;
map[k].len=a;
map[k].s=i;
map[k++].e=j;
}
}
scanf("%d",&m);
for (i=1;i<=m;i++)
{
scanf("%d%d",&s,&e);
Union(s,e);
}
sort(map,map+k,cmp);
Kul();
return 0;
}





 

posted @ 2011-11-24 16:50  104_gogo  阅读(156)  评论(0编辑  收藏  举报