kruskal算法基于并查集的实现

#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;

/*并查集start*/ 
struct UF{

		UF * parent;

		UF():parent(NULL){	}

};
UF* find(UF* c){
	if(c->parent == NULL)
		return c;
	set<UF*> s;
	while(c->parent!= NULL){
		s.insert(c);
		c = c->parent;
	}
	for(auto v : s)
		v->parent = c;
	return c;
}
void unionn(UF *a ,UF* b){
	if(find(a) == find(b))
		return;
	find(a)->parent = find(b);
}
UF uf[100];
/*并查集end*/

/*边的结构*/ 
struct Edge{  
	int from,to;
	int weight;
	Edge(int a,int b, int c):from(a),to(b),weight(c){	}
	bool operator< (const Edge& other) const{
		return weight<other.weight;
	}
};

vector<Edge> e;   //存储所有的边 
vector<Edge>  g[100];  //存储生成的图 ,以邻接表表示 
int N,M;    //顶点个数,边的条数 

bool kruskal(){
	sort(e.begin(), e.end());
	int cnt = 0;
	for(int i=0; i<e.size();++i){
		int from = e[i].from;
		int to =e[i].to;
		int weight = e[i].weight;
		if(find(&uf[from]) == find(&uf[to]))
			continue;
		unionn(&uf[from],&uf[to]);
		g[from].push_back(Edge(from,to,weight));
		g[to].push_back(Edge(to,from,weight));
		cnt++;
		if(cnt == N-1)
			return true;
	}
	return false;
}

int main()
{
	cin>>N>>M;
	for(int i=0; i<M; ++i)
		{
			int from,to,weight;
			cin>>from>>to>>weight;
			e.push_back(Edge(from,to,weight));
			
		}
	if(kruskal())
		for(int i=1; i<=N;++i)
			for(auto v : g[i])
				cout<<v.from<<" "<<v.to<<" "<<v.weight<<endl; //输出生成的图的所有边 
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值