Borůvka求最小生成树

#include<bits/stdc++.h>
using namespace std;

const int N = 5010;
const int M = 2e5 + 10;
struct Node {
    
    
	int a, b, c;
}e[M];
int vis[M];
int p[N], bst[N];
int n, m;

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

bool Better(int x, int y) {
    
    
	if(!y) return true;
	if(e[x].c == e[y].c) return x < y;
	return e[x].c < e[y].c; 
}

int main()
{
    
    
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= m; ++i) scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].c);
	for(int i = 1; i <= n; ++i) p[i] = i;
	
	int cnt = 0, sum = 0;
	int update = 1;
	while(update) {
    
    
		update = 0;
		memset(bst, 0, (n + 1) * sizeof(int));
		
		for(int i = 1; i <= m; ++i) {
    
    
			if(vis[i]) continue;
			int a = find(e[i].a), b = find(e[i].b);
			if(a == b) continue;
			
			if(Better(i, bst[a])) bst[a] = i;
			if(Better(i, bst[b])) bst[b] = i;
		}
	
		for(int i = 1; i <= n; ++i) 
			if(bst[i] && !vis[bst[i]]) {
    
    
				update = 1;
				++cnt;
				sum += e[bst[i]].c;
				vis[bst[i]] = 1;
				p[find(e[bst[i]].a)] = find(e[bst[i]].b);
			}
		
	}
	if(cnt == n - 1) printf("%d\n", sum);
	else puts("orz");
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43900869/article/details/109387021