GRL_2_A:Minimum Spanning Tree

题目链接

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

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

思路:

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.在写并查集的合并操作时,要注意

if(find(x)!=find(y)) 
   pre[find(y)]=find(x);

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值