对于60%的数据,有1≤n≤103。
 对于100%的数据,有1≤n≤5×105,1≤v≤103,1≤x,y≤n。
题解:
按边权从大到小,枚举边权的贡献,对于每个块更新一下ans数组的值即可;ans[i]表示在i所在的块中某一结点到其他结点d总和的最大值。
AC代码:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn=5e5+50;
 5 struct node
 6 {
 7     int x,y,w;
 8 }stu[maxn];
 9 bool cmp(node p,node q)
10 {
11     return p.w>q.w;
12 }
13 int n,pre[maxn],sz[maxn],ans[maxn];
14 int fin(int x)
15 {
16     int boss=x;
17     while(boss!=pre[boss]) boss=pre[boss];
18     while(x!=pre[x]){
19         int cnt=pre[x];
20         pre[x]=boss;
21         x=cnt;
22     }
23 }
24 int main()
25 {
26     scanf("%d",&n);
27     for(int i=1;i<n;i++){
28         scanf("%d %d %d",&stu[i].x,&stu[i].y,&stu[i].w);
29     }
30     sort(stu+1,stu+n+1,cmp);
31     for(int i=1;i<=n;i++){
32         sz[i]=1;pre[i]=i;
33     }
34     for(int i=1;i<n;i++){
35         int x=fin(stu[i].x);
36         int y=fin(stu[i].y);
37         int val=max(ans[x]+sz[y]*stu[i].w,ans[y]+sz[x]*stu[i].w);
38         pre[x]=y;
39         sz[y]+=sz[x];
40         ans[y]=val;
41     }
42     printf("%d\n",ans[fin(n)]);
43     return 0;
44 }
 
View Code