您的位置:首页 > 其它

POJ 2421 Constructing Roads(并查集+最小生成树)

2016-03-18 10:43 471 查看
题目链接:

POJ 2421 Constructing Roads

题意:

给出n个点两两之间的权值,然后有m对a,b,表示a,b已经连通了。

问将这n个点都连通最少权值和是多少。

分析:

将m对已连通的点对用并查集合并,然后用Kruskal算法即可。

CODE:

//804K 47MS
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const int maxn=110;

int n,ans,tot,m,u,v,w;
int pre[maxn];

struct Edge{
int u,v,w;
}edge[maxn*maxn];

void init()
{
ans=tot=0;
for(int i=0;i<maxn;i++)
pre[i]=i;
}

bool cmp(struct Edge a,struct Edge b)
{
return a.w<b.w;
}

int find(int x)
{
return pre[x]==x?x:pre[x]=find(pre[x]);
}

void mix(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy) pre[fx]=fy;
}

int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
#endif
while(~scanf("%d",&n))
{
init();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&edge[tot].w);
edge[tot].u=i;
edge[tot].v=j;
tot++;
}
}
sort(edge,edge+tot,cmp);
scanf("%d",&m);
for(int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
mix(u,v);
}
for(int i=0;i<tot;i++)
{
u=edge[i].u;
v=edge[i].v;
w=edge[i].w;
int fu=find(u);
int fv=find(v);
//printf("u=%d fu=%d v=%d fv=%d\n",u,fu,v,fv);
if(fu!=fv)
{
pre[fu]=fv;
ans+=w;
}
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kruskal 最小生成树