图论--Kruskal算法

#include
using namespace std;
const int N = 1e6 + 7;

int n,m;
struct node{
	int x,y,z;
};
node a[N];
int fa[N],sum,cnt;

void init(int n){
	for(int i = 1; i <= n; i++)
	fa[i] = i;
}

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

void krusal() {
	sort(a + 1, a + m + 1, [](node q,node w) {
		return q.z < w.z;
	});
	for(int i = 1; i <= m; i++) {
		int x = find(a[i].x);
		int y = find(a[i].y);
		if(x == y) continue;
		fa[x] = y;
		sum += a[i].z;
		cnt++;
		if(cnt == n - 1) break;
	}
}

int main( ) {
	cin >> n >> m;
	for(int i = 1; i <= m; i++) 
	cin >> a[i].x >> a[i].y >> a[i].z;
	init(n);
	krusal();
	cout << sum;
	
	return 0;
}

 练习::3210. 最优灌溉 - AcWing题库

你可能感兴趣的:(算法,图论,c++)