kruskal算法就是在并查集基础上加了个贪心,算法正确性的证明看完算法导论自己还不怎么懂,不过感觉写走来比起prim要来得顺手得多
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class node{
public:
int x;
int y;
int dis;
};
bool cmp(node& lhs,node& rhs){
return lhs.dis < rhs.dis;
}
int n;
vector<node> way;
vector<int> father;
int find_father(int x){
if(x == father[x])
return x;
else{
father[x] = find_father(father[x]);//压缩路径
}
return father[x];
}
void merge(int a,int b){
father[a] = b;
}
int Mst_kruskal(){
int res = 0;
sort(way.begin(),way.end(),cmp);//贪心排序
int temp = n*(n-1)/2;
for(int i = 0;i <= n;i++){//初始化父结点
father.push_back(i);
}
for(int i = 0;i < temp;i++){
int fx = find_father(way[i].x);
int fy = find_father(way[i].y);
if(fx != fy){
res += way[i].dis;
merge(fx,fy);
}
}
return res;
}
int main()
{
while(scanf("%d",&n)==1 && n){
int temp = n*(n-1)/2;
for(int i = 0;i < temp;i++){
node a;
scanf("%d %d %d",&a.x,&a.y,&a.dis);
way.push_back(a);
}
printf("%d\n",Mst_kruskal());
way.clear();//注意清空
father.clear();
}
return 0;
}