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

HDU 4424 Conquer a New Region (并查集)

2017-07-25 10:49 309 查看
题意:给定一棵树,让你选一个中心城市,问你中心城市到所有其他城市的权值和最小,每条路的权值是该边上和最小权值。

析:从大到小枚举边,然后用并查集进行维护,在合并两个集合时,要考虑两边集合加上该边的的最大的那一个,每次要取最大值。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#include <list>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 2e5 + 10;
const LL mod = 1e12;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}

int p[maxn];
int num[maxn];
LL sum[maxn];
struct Node{
int u, v, w;
bool operator < (const Node &p) const{
return w > p.w;
}
};
Node a[maxn];

int Find(int x){ return x == p[x] ? x : p[x] = Find(p[x]); }

int main(){
while(scanf("%d", &n) == 1){
for(int i = 0; i < n-1; ++i)  scanf("%d %d %d", &a[i].u, &a[i].v, &a[i].w);
memset(sum, 0, sizeof sum);
for(int i = 0; i <= n; ++i){
p[i] = i;
num[i] = 1;
}
sort(a, a + n - 1);
for(int i = 0; i < n-1; ++i){
int x = Find(a[i].u);
int y = Find(a[i].v);
LL tmp1 = sum[x] + (LL)num[y] * a[i].w;
LL tmp2 = sum[y] + (LL)num[x] * a[i].w;
sum[x] = max(tmp1, tmp2);
num[x] += num[y];
p[y] = x;
}
printf("%I64d\n", sum[Find(1)]);
}
return 0;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: