您的位置:首页 > 产品设计 > UI/UE

Conquer a New Region UVA - 1664

2017-11-02 17:52 330 查看
按照并查集的方法来做,首先读入相应的信息,然后按照边的大小,由大到小进行排序,然后依次处理,因为边是按照降序处理的,这样就不会导致错误,同时注意记录容量和的变量要设置为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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: