計蒜客-穿越雷區-Kruscal最小生成樹

題目鏈接

水題做多了有害身體健康?
AC代碼

#include<bits/stdc++.h>

using namespace std;
const int maxn = 30005;
const int maxm = 50005;
int n, m, fa[maxn], ans, cnt;

struct edge{
	int u, v, w;
	edge(int uu, int vv, int ww){
		u = uu, v = vv, w = ww;
	}
	bool operator < (const edge a) const{
		return w > a.w;
	}
};
priority_queue<edge>que;

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

int getf(int a){
	if(a == fa[a])
		return a;
	return fa[a] = getf(fa[a]);
}

bool sam(int u, int v){
	return getf(u) == getf(v);
}

void merge(int u, int v){
	fa[getf(u)] = getf(v);
}

int main(){
	cin>>n>>m;
	init();
	int x, y, z;
	for(int i = 0; i < m; i++){
		scanf("%d%d%d", &x, &y, &z);
		que.push(edge(x, y, z));
	}
	while(cnt != 1){
		edge temp = que.top();
		que.pop();
		if(!sam(temp.u, temp.v)){
			merge(temp.u, temp.v);
			cnt--;
			ans += temp.w;
		}
	}
	cout<<ans<<endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章