GRL_2_A:Minimum Spanning Tree

题目链接

题目给出一个有权无向图,要求出其最小生成树(输出最小生成树的各边权值之和);

由于边数比较多,采用cruskal算法,存储的时候以边的形式存储;

思路:

1.先按权值给边从小到大排序;

2.初始化并查集,所有点在不同集合内;

3.从小到大开始选取边,如果该边的两个顶点在同一集合内,则跳过这个边;如果该边的两个顶点不在同一集合内,则将这条边加入到最小生成树中;(集合可以理解成子树,如果不在同一集合,那就说明这条边连接了两个不同的子树,则这条边是当前所有未使用的边中全职最小,而且有效的边)直到所有顶点都处于同一并查集内;

代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
const int maxx=100010;
const int inf=0x7fffffff;
int v,e,ans=0;
class edge{
	public:
		int source,target,cost;
		edge(int source,int target,int cost):
			source(source),target(target),cost(cost){}
		bool operator < (const edge &e ) const {
			return cost<e.cost;
		}	
};

vector<edge > A;
int pre[maxx];

int find(int u){
	if(pre[u]!=u) pre[u]=find(pre[u]);
	return pre[u];	
}

void hebing(int x,int y){
	if(find(x)!=find(y)) pre[find(y)]=find(x);
	return ;
}

int main (){
	cin>>v>>e;
	if(e==0) {
		cout<<"0"<<endl;return 0;
	}
	int x,y,z;
	while(e--){
		cin>>x>>y>>z;
		A.push_back(edge(x,y,z));
	}
	sort(A.begin(),A.end());
	for(int i=0;i<v;i++) pre[i]=i;
	for(int i=0;i<A.size();i++){
//		for(int i=0;i<v;i++){
//			cout<<i<<"  "<<pre[i]<<endl;
//		}cout<<endl;
		if(find(A[i].source)!=find(A[i].target)) {
			hebing(A[i].source,A[i].target);
			ans+=A[i].cost;
			//cout<<A[i].source<<"  "<<A[i].target<<"  "<<A[i].cost<<endl;
		}
	}
	cout<<ans<<endl;
	return 0;
	
}

错点:

1.要考虑到边数为0的情况,在边数为0时,输出0

2.在写并查集的合并操作时,要注意

扫描二维码关注公众号,回复: 2233312 查看本文章
if(find(x)!=find(y)) 
   pre[find(y)]=find(x);

3.在类定义时,有构造函数的成员列表,注意缺省写法;


猜你喜欢

转载自blog.csdn.net/qq_33982232/article/details/80975761