克鲁斯卡尔算法求最大/最小生成树
仅有粗略的算法解释。
标准题目
给定一个图,有n个点m个边,要求找到这个图的最小生成树
输入输出格式
输入:
第一行:n,m
下面m行:x,y,v,表示点xy之间有一个长度是v的点。
输出:
第一行:最小生成树的总长度
下面n行:最小生成树(第i个点和那些点有边?)
样例
输入:
9 14
1 2 4
2 3 8
3 4 7
4 5 9
5 6 10
6 7 2
7 8 1
8 9 7
2 8 11
3 9 2
7 9 6
3 6 4
4 6 14
1 8 8
输出
37
1: 2
2: 1 3
3: 9 6 4 2
4: 3 5
5: 4
6: 7 3
7: 8 6
8: 7
9: 3
样例解释
在8和7之间加一个长度是1的边
在7和6之间加一个长度是2的边
在9和3之间加一个长度是2的边
在2和1之间加一个长度是4的边
在6和3之间加一个长度是4的边
在4和3之间加一个长度是7的边
在3和2之间加一个长度是8的边
在5和4之间加一个长度是9的边
大致思路
- 把所有边按照边长排序
- 从1到m枚举边,如果边的两端点不在一个集合中,便加上这条边,然后把这两个端点堆在一个集合中(并查集优化)
- 所有点都在一个集合中(生成树完成),无法继续加边,算法结束,输出结果。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
int n,m,an[23333],ans=0,k,frog;
struct po {
int x,y,v;
} a[10000];
struct tp{
int p,dis;
};
vector<tp> tree[23333];//数组模拟邻接表
bool cmp(po A,po b) {
return A.v<b.v;
}
int find(int x) {
if(an[x]==x)
return an[x];
else {
an[x]=find(an[x]);
return an[x];
}
}
void myunion(int x,int y) {
if(find(x)!=find(y))
an[find(x)]=find(y);
}
void Dadd(int A,int b,int v){
tp temp;temp.p=b,temp.dis=v;
tree[A].push_back(temp);
}
int main() {
ios::sync_with_stdio(false);
cin>>n>>k;
for(int i=1; i<=k; i++) {
int x,y,v;
cin>>x>>y>>v;
a[i].x=x;a[i].y=y;a[i].v=v;
ans=0;
}
for(int i=1; i<=n; i++)
an[i]=i;
//算法开始:
sort(a+1,a+k+1,cmp);
for(int i=1; i<=k; i++) {
if( find(an[a[i].x]) != find(an[a[i].y]) ) {
ans+=a[i].v;
myunion(a[i].x,a[i].y);
Dadd(a[i].x,a[i].y,a[i].v);
Dadd(a[i].y,a[i].x,a[i].v);
}
}
//算法结束,输出。
cout<<ans<<endl;
for(int i=1;i<=n;i++){
cout<<i<<": ";
int s=tree[i].size();
for(int j=0;j<s;j++){
cout<<tree[i][j].p<<" ";
}
cout<<endl;
}
return 0;
}
补充
如果想找到最大生成树,只需改变排序顺序即可,本质上是贪心的思想。