题目来源:POJ 1287
简单题目分析:
给你若干点,以及两点间的距离,求将所有点连通的最小距离。
思路:最小生成树(MST),并查集+Kruskal算法。
Kruskal算法采用贪心策略,将每个边的权值按从小到大排序。首先生成一个与原图相同的点集,每次贪心权值最小的边,如果这个边连接的两个顶点没有连通(无论是直接连通还是间接连通),那么把这个边加上,如果两个顶点已经连通,则跳过这条边,直到图中已经存在n-1条边(n个顶点的图)。
其中并查集的作用是判断两个顶点是否连通。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define MAXN 10000
using namespace std;
struct node
{
int first;
int second;
int len;
}temp[MAXN];
int pre[MAXN];
int findRoot(int x)
{
while(x!=pre[x])
x=pre[x];
return x;
}
bool cmp(node a,node b)
{
return a.len<b.len;
}
int main()
{
int p,r;
while(~scanf("%d",&p) && p!=0)
{
scanf("%d",&r);
int ans=0,cnt=0;
int i;
for(i=1;i<=p;++i)
pre[i]=i;
for(i=0;i<r;++i)
scanf("%d %d %d",&temp[i].first,&temp[i].second,&temp[i].len);
sort(temp,temp+r,cmp);
for(i=0;i<r;++i)
{
if(cnt==p-1)
break;
else
{
if(findRoot(temp[i].first)!=findRoot(temp[i].second))
{
pre[findRoot(temp[i].second)]=findRoot(temp[i].first);
cnt++;
ans+=temp[i].len;
}
}
}
printf("%d\n",ans);
}
return 0;
}
ps:这个题在vjudge(校内训练)上数据比较水,代码敲错了依然AC...回到寝室在POJ又提交一遍,发现RUNTIME ERROR,最后发现数组开小了。题目中说最多有50个顶点,那么最多就会有1225条边,然后把数组直接开成10000 Orz (逃