带路径压缩的并查集模板:
class UnionFind{
public:
vector<int>father;
UnionFind(int num){//num表示元素的个数
for(int i = 0; i < num; i++){
father.push_back(i);//箭头指向自己
}
}
int Find(int n){
//递归
if(father[n] == n)
return n;
father[n] = Find(father[n]);//路径压缩版本
return father[n];
}
void Union(int a, int b){
int fa = Find(a);
int fb = Find(b);
father[fb] = fa;
}
};
Kruscal简单模板:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
int n,p;
int node[10001];
int f[10001];
struct E{
int x,y,d; //x、y 结点间距离
}e[100001];
bool cmp(E e1, E e2){
return e1.d < e2.d;
}
int find(int x){
return f[x] == x ? x : f[x] = find(f[x]);
}
void merge(int x,int y){
int tx = find(x);
int ty = find(y);
if(tx != ty){
f[ty] = tx;
}
}
bool same(int x,int y){
return find(x) == find(y);
}
int Kruscal(){
int ans = 0;
sort(e,e+p,cmp);
for(int i = 0; i < p; i++){
if(!same(e[i].x,e[i].y)){
merge(e[i].x,e[i].y);
ans += e[i].d;
}
}
return ans;
}
void init(){
scanf("%d%d",&n,&p);
for(int i = 1; i <= p; i++){
scanf("%d%d%d",&e[i].x, &e[i].y, &e[i].d);
}
for(int i = 1; i <= n; i++){
f[i] = i;
}
}
int main(){
init();
int result = Kruscal();
for(int i = 1;i <= n;i++){
if(!same(i,1)){
result = -1;
}
}
if(result != -1){
cout << result << endl;
}else{
cout << "orz" << endl;
}
return 0;
}