Problem Description
某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
思路
并查集,非常的裸。
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
const int N=10000+5;
const int M=100+5;
int n,m,num,x,y,ans=0,father[M];
struct node
{
int u,v,w;
}ed[N];
int cmp(node a,node b)
{
return a.w<b.w;
}
int getfather(int x)
{
if (father[x]==x) return x;
else return getfather(father[x]);
}
int main()
{
while(scanf("%d%d",&n,&m),n)
{
ans=0;
for (int i=1;i<=m;i++)
father[i]=i;
for (int i=1;i<=n;i++)
scanf("%d%d%d",&ed[i].u,&ed[i].v,&ed[i].w);
sort(ed+1,ed+n+1,cmp);
for (int i=1;i<=n;i++)
{
x=getfather(ed[i].u);
y=getfather(ed[i].v);
if (x!=y)
{
ans+=ed[i].w;
father[x]=y;
}
}
num=0;
for (int i=1;i<=m;i++)
if (father[i]==i) num++;
if (num==1)
printf("%d\n",ans);
else puts("?");
}
return 0;
}