洛谷 P1340 兽径管理

这道题也就是一个在线的最小生成树(虽然可以转化为离线但是懒嘛),因为给的是边,那么就是Kruskal算法了。由于在求解中需要排序,而因为序列本身是有序时插入一个数据,那么我们就可以直接用插入排序的思想做。

代码:

#include <bits/stdc++.h>
using namespace std;
struct node{
	int l , r , w;
};
vector<node> e;
int n , m , now , tot , ans;
int fa[210];
int find(int x){
	if(fa[x] == x) return x;
	return fa[x] = find(fa[x]);
}
bool cmp(node x , node y){
	return x.w < y.w;
}
int main(){
	cin >> n >> m;
	while(m--){
		int xx , yy , zz;
		tot++;
		cin >> xx >> yy >> zz;
		int k = 0;
		for(int i = 0; i < tot - 1; i++){
			if(zz < e[i].w) break;
			k++;
		}
		node bzzs;
		bzzs.l = xx , bzzs.r = yy , bzzs.w = zz; 
		e.insert(e.begin() + k , bzzs);
		if(tot < n - 1){
			cout << -1 << endl;
			continue;
		}
		for(int i = 1; i <= n; i++) fa[i] = i;
		now = 0 , ans = 0;
		for(int i = 1; i <= tot; i++){
			if(now == n - 1) break;
			int x = find(e[i - 1].l) , y = find(e[i - 1].r);
			if(x == y) continue;
			now++;
			ans += e[i - 1].w;
			fa[x] = y;
		}
		if(now != n - 1) cout << -1 << endl;
		else cout << ans << endl;
	}
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/bzzs/p/13204943.html
今日推荐