1 题目编号:1004
2 题目内容:
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3 5 <div style='font-family:Times New Roman;font-size:14px;background-color:F4FBFF;border:#B7CBFF 1px dashed;padding:6px'><div style='font-family:Arial;font-weight:bold;color:#7CA9ED;border-bottom:#B7CBFF 1px dashed'><i>Hint</i></div>Hint</div> Huge input, scanf is recommended.
3 解题思路形成过程:起初让每个村庄自身各为一个集合,设根结点就是自己本身(设根结点的目的就是为了方便查询并合并),同时又用到了最小生成树的克鲁斯卡尔算法,即让每两个村庄的距离从小到大依次排序,然后从小开始遍历两个村庄,先判断这两个村庄的根结点是否相同; 如果不同,说明在不同的集合,则开始合并他们,并把他们的距离加起来; 如果根结点相同,则在同一个集合,这时候就不能连他们了(克鲁斯卡尔算法中不能产生回路)。
4 代码:
#include <cstdio>
#include <algorithm>
using namespace std;
int f[103]; //村庄的个数,节点
struct ss
{
int x,y,z;
}a[5000];
bool cmp(ss a,ss b)
{ return a.z<b.z; }
int find(int x)
{
return f[x]==x ? x : find(f[x]); //查询操作:返回的是x的根结点
}
int main()
{
int N,n,i,b,c;
while(scanf("%d",&N),N)
{
int s=0;
n=N*(N-1)/2;
for(i=1;i<=N;i++) //初始化 ,一开始每个村庄都是一个单独的集合,编号从1到n
f[i]=i;
for(i=1;i<=n;i++)
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);
sort(a+1,a+1+n,cmp);
for(i=1;i<=n;i++)
{
int b=find(a[i].x);
int c=find(a[i].y);
if(b==c)continue;
f[c]=b; <span style="white-space:pre"> </span>//合并操作
s+=a[i].z;
}
printf("%d\n",s);
}
return 0;
}