当前位置:网站首页>AcWing 1141. LAN problem solving (kruskalkruskal finding the minimum spanning tree)

AcWing 1141. LAN problem solving (kruskalkruskal finding the minimum spanning tree)

2022-07-07 01:36:00 Mr. Qiao Da

AcWing 1141. LAN
Cruz Carr seeks the minimum generated forest ( Is to find the minimum spanning tree for each connected block ), Kruskal's algorithm process is just to add edges to the set in turn from small to large , So here we just use Kruskal algorithm to find

#include<bits/stdc++.h>

using namespace std;

const int N = 210;

int p[N];  // Merge ancestor array 
int n, m;
int res;  // Record answer 
struct Edge{
    
	int a, b, w;
	bool operator<(const Edge &t) const {
    
		return w < t.w;
	}
}edge[N]; 

int find(int x){
    
	if(p[x] != x) p[x] = find(p[x]);
	return p[x];
}

int main()
{
    
	cin>>n>>m;
	for(int i = 1; i <= n; i ++ ) p[i] = i;  // Pay attention to initialization and set lookup  
	for(int i = 0; i < m; i ++ ){
    
		int a, b, c;
		cin>>a>>b>>c;
		edge[i] = {
    a, b, c};
	}
	
	sort(edge, edge + m);
	
	for(int i = 0; i < m; i ++ ){
    
		//a and b Connected will be traversed to , So there is no need to worry about connecting two different connected blocks  
		int a = find(p[edge[i].a]), b = find(p[edge[i].b]);
		if(a != b) p[a] = b;  // If not in a set , Just join a set  
		else res += edge[i].w;  // If these two points are in a connection block , It means that they have been connected by the side with less cost , At present, this side can be deleted  
	}
	cout<<res<<endl;
	return 0;
}


原网站

版权声明
本文为[Mr. Qiao Da]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061800128842.html