题解:这道题是一道树的题,但是解法其实和树没什么关系。首先将边从大到小排列,然后依次插入到并查集中再依次结合,判断哪种插入的边怎样打掉集合才是最优的。然后依次计算既可
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <map>
using namespace std;
const int maxn = 200000 + 100;
int fa[maxn];
struct node
{
int to, next;
int len;
} p[maxn];
int e;
struct nod
{
int num;
long long sum;
} pp[maxn];
void init()
{
memset(fa, -1, sizeof(fa));
e = 0;
for (int i = 0; i < maxn; i ++)
{
pp[i].num = 1;
pp[i].sum = 0;
}
}
int findnum(int x)
{
if (fa[x] == -1)
return x;
return fa[x] = findnum(fa[x]);
}
bool cmp(node x, node y)
{
return x.len > y.len;
}
long long ans;
void unio(int x, int y, int len)
{
int xx = findnum(x);
int yy = findnum(y);
// cout <<"xx:"<<xx<<"sum:" <<pp[xx].sum <<endl;
//pp[xx].num = pp[xx].num + pp[yy].num;
// cout <<"xx:"<<xx<<"num:"<< pp[xx].num <<endl;
pp[xx].sum = max(pp[xx].sum + (long long)len * pp[yy].num, pp[xx].num * (long long)len + pp[yy].sum);
//cout <<"xx:"<<xx<<"sum:" <<pp[xx].sum <<endl;
pp[xx].num = pp[xx].num + pp[yy].num;
// cout <<"xx:"<<xx<<"num:"<< pp[xx].num <<endl;
ans = max(pp[xx].sum, ans);
fa[yy] = xx;
}
int main()
{
int n;
int a, b, c;
while (~scanf("%d", &n)) {
init();
for (int i = 0; i < n - 1; i ++)
{
scanf("%d%d%d", &a, &b, &c);
p[e].to = a;
p[e].next = b;
p[e].len = c;
e ++;
}
ans = 0;
sort(p, p + e, cmp);
for (int i = 0; i < e; ++i)
{
unio(p[i].to, p[i].next, p[i].len);
}
printf("%lld\n", ans);
}
}