Problem Description
3 1 2 1 2 3 2 5 1 2 2 2 3 5 2 4 7 3 5 4
Case #1: 1 Case #2: 17Hinthuge input,fast IO method is recommended. In the first sample: The maxValue is 1 and minValue is 1 when they select city 1 and city 2, the experience of love is 0. The maxValue is 2 and minValue is 2 when they select city 2 and city 3, the experience of love is 0. The maxValue is 2 and minValue is 1 when they select city 1 and city 3, the experience of love is 1. so the sum of all experience is 1;
#include <cstdio>
#include <algorithm>
#define ull unsigned long long
using namespace std;
int const MAX = 150005;
int fa[MAX], cnt[MAX], n;
ull ma, mi;
struct Edge
{
int u, v;
ull val;
}e[MAX];
bool cmp(Edge a, Edge b)
{
return a.val < b.val;
}
void init()
{
for(int i = 0; i <= n; i++)
{
fa[i] = i;
cnt[i] = 1;
}
}
int Find(int x)
{
return x == fa[x] ? x : fa[x] = Find(fa[x]);
}
int Union(int a, int b, ull val, bool flag)
{
int r1 = Find(a);
int r2 = Find(b);
if(flag)
ma += (ull)cnt[r1] * cnt[r2] * val;
else
mi += (ull)cnt[r1] * cnt[r2] * val;
fa[r1] = r2;
cnt[r2] += cnt[r1];
}
int main()
{
int ca = 1;
while(scanf("%d", &n) != EOF)
{
for(int i = 1; i <= n - 1; i++)
scanf("%d %d %llu", &e[i].u, &e[i].v, &e[i].val);
sort(e + 1, e + n, cmp);
init();
ma = 0;
for(int i = 1; i <= n - 1; i++)
Union(e[i].u, e[i].v, e[i].val, true);
init();
mi = 0;
for(int i = n - 1; i >= 1; i--)
Union(e[i].u, e[i].v, e[i].val, false);
printf("Case #%d: %llu\n", ca++, ma - mi);
}
}HDU 5176 The Experience of Love (带权并查集 + 贪心)
原文:http://blog.csdn.net/tc_to_top/article/details/43876481