解题思路:kruskal算法:贪心选取最短的边构成一棵最小的生成树
共n个点,即先将所有的边排序,然后利用并查集判断,如果两点连通,则不加入树,不连通,则加入树,直到加入了n-1条边,构成生成树。
反思:仔细edge的排序,wa了好多次因为这个
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 27773 Accepted Submission(s): 12376
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,pre[10010];
struct Edge
{
int u,v,w;
} edge[10010];
bool cmp(Edge n1,Edge n2)
{
return n1.w<n2.w;
}
int find(int root)
{
return root == pre[root] ? root : pre[root] = find(pre[root]);
}
int unionroot(int x,int y)
{
int root1=find(x);
int root2=find(y);
if(root1==root2)
return 0;
pre[root1]=root2;
return 1;
}
int kruskal(int n)
{
int ans=0,i,x,y,sum=0;
sort(edge+1,edge+n*(n-1)/2+1,cmp);//注意这儿edge的排序是加到n*(n-1)/2+1
for(i=1;i<=n*(n-1)/2;i++)
{
x=edge[i].u;
y=edge[i].v;
if(unionroot(x,y))
{
ans+=edge[i].w;
sum++;
if(sum==n-1)
break;
}
}
return ans;
}
int main()
{
int n,i,j;
while(scanf("%d",&n)!=EOF&&n)
{
for(i=1;i<=10010;i++)
pre[i]=i;
for(i=1;i<=n*(n-1)/2;i++)
scanf("%d %d %d",&edge[i].u,&edge[i].v,&edge[i].w);
printf("%d\n",kruskal(n));
}
}
原文:http://www.cnblogs.com/wuyuewoniu/p/4249261.html