为了学习最小生成树 这两天学习了并查集 做并查集的题碰到了一道最小生成树 自己搞定了这道题 非常的高兴哈~
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
int father[101];
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
void makeset(int n)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
for(int i=1;i<=n;i++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
father[i]=i;
}
}
int findset(int x)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
if(father[x]!=x)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
father[x]=findset(father[x]);
}
return father[x];
}
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
int Union(int a,int b)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
int x=findset(a);
int y=findset(b);
if(x==y)
return 1;//如果两个点在同一颗树中 那么这两个点添加以后会形成回路 返回1
else
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
father[x]=y;
return 0;
}
}
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
struct country
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
int first;
int second;
int distance;
}a[5001];
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
bool cmp(country x,country y)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
return x.distance<y.distance;
}
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
int main()
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
int n;
while(scanf("%d",&n)!=EOF)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(n==0)
break;
makeset(n);
int sum=0;
for(int i=1;i<=n*(n-1)/2;i++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
scanf("%d %d %d",&a[i].first,&a[i].second,&a[i].distance);
}
sort(a+1,a+n*(n-1)/2+1,cmp);//将距离从小到大的排序
for(int i=1;i<=n*(n-1)/2;i++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(Union(a[i].first,a[i].second)==0)//如果两个点在同一颗树中 那么这两个点添加以后会形成回路 否则这两个点之间的路加入到最小生成树中
sum=sum+a[i].distance;
}
printf("%d\n",sum);
}
return 0;
}