【模板】最小生成树
一、kruskal
#include<cstdio>
#include<algorithm>
using namespace std;
const int NN = 5e3+8, MM = 2e5+8;
int N, M;
int ans,cnt;
int fa[NN];
struct Edge{
int from,to,len;
#define f(x) edge[x].from
#define t(x) edge[x].to
#define len(x) edge[x].len
bool operator < (const Edge &x) const{
return len < x.len;
}
}edge[MM];
int find(int x){
if(x == fa[x]) return x;
return fa[x] = find(fa[x]);
}
void merge(int x,int y){//把y连在x上
fa[find(x)] = fa[find(y)];
}
void add_edge(int i){
merge(f(i),t(i));
ans += len(i);
}
int main(){
scanf("%d%d",&N,&M);
for(int i = 1; i <= N; i++) fa[i] = i;
for(int i = 1; i <= M; i++) scanf("%d%d%d",&f(i),&t(i),&len(i));
sort(edge + 1, edge + 1 + M);
for(int i = 1; i <= M; i++){
int X = find(f(i)),Y = find(t(i));
if(X != Y)
add_edge(i);
}
for(int i = 1; i <= N; i++)
if(fa[i] == i) ++cnt;
if(cnt == 1) printf("%d",ans);
else printf("orz");
}
本文来自博客园,作者:ricky_lin,转载请注明原文链接:https://www.cnblogs.com/rickylin/p/17049915.html