【模板】最小生成树——Kruskal算法
Kruskal算法(n*n+m)
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<queue>
#include<stack>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
const int INF= 0x3f3f3f3f;
struct MS
{
int u, v, w;
}gr[500001];
int fa[500100];
int n, m;
bool cmp(MS X,MS Y)
{
return X.w < Y.w;//结构体重载
}
int findx(int x)//并查集
{
if(x!=fa[x])
fa[x] = findx(fa[x]);
return fa[x];
}
void unity(int x,int y)//祖先合并
{
int x1 = findx(x);
int y1 = findx(y);
if(x1!=y1)
fa[x1] = y1;
}
void make_out()//初始化并查集
{
for (int i = 1; i<= n;i++)
{ fa[i] = i;
}
}
int main()
{
cin >> n >> m;
int total = 0;
for (int i = 1; i<= m;i++)
{
cin >> gr[i].u >> gr[i].v >> gr[i].w;
}
make_out();
sort(gr + 1, gr + m + 1, cmp);//根据权值从小到大排序
for (int i = 1; i<= m;i++)
{
int u1 = gr[i].u;
int v1 = gr[i].v;
if(findx(u1)!=findx(v1))
{
total += gr[i].w;
unity(u1, v1);
}
}
int ans = 0;
for (int i = 1; i <= n;i++)
{
if(fa[i]!=i)//判断是不是联通图
ans++;
}
if(ans==n-1)
cout << total;
else{
cout << "orz";
}
return 0;
}