Conquer a New Region UVA - 1664

按照并查集的方法来做,首先读入相应的信息,然后按照边的大小,由大到小进行排序,然后依次处理,因为边是按照降序处理的,这样就不会导致错误,同时注意记录容量和的变量要设置为long long,不然会出现溢出错误,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;

typedef long long ll;

class Edge{
public:
	ll a, b, c;
};

bool compare(const Edge& a, const Edge& b){
	return a.c > b.c;
}

int parent[200010];
ll total[200010];
int amount[200010];

class Solve{
public:
	int N;
	vector<Edge> edge;
	
	void Init(){
		edge.clear();
		for (int i = 0; i < N - 1; i++){
			Edge temp;
			cin >> temp.a >> temp.b >> temp.c;
			edge.push_back(temp);
		}
		for (int i = 1; i <= N; i++){
			parent[i] = i; total[i] = 0; amount[i] = 1;
		}
		sort(edge.begin(),edge.end(),compare);
	}

	int find_root(int i){
		if (parent[i] == i) return i;
		return find_root(parent[i]);
	}

	void Deal(){
		Init();
		ll ans = 0;
		for (int i = 0; i < edge.size(); i++){
			int root_a = find_root(edge[i].a);
			int root_b = find_root(edge[i].b);
			ll suma = total[root_a] + amount[root_b] * edge[i].c;
			ll sumb = total[root_b] + amount[root_a] * edge[i].c;
			if (suma > sumb){
				parent[root_b] = root_a; total[root_a] = suma;
				ans = suma; amount[root_a] += amount[root_b];
			}
			else{
				parent[root_a] = root_b; total[root_b] = sumb;
				ans = sumb; amount[root_b] += amount[root_a];
			}
		}
		cout << ans << endl;
	}
};

int main(){
	Solve a;
	while (cin >> a.N){
		a.Deal();
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值