两遍DFS。第一遍统计以每个点为根的子树大小,第二遍更新答案。

 1 #include<cstdio>
 2 #include<iostream>
 3 using namespace std;
 4 int v[2000001],w[2000001],first[2000001],next[2000001],en,sz[1000001];
 5 bool vis[1000001];
 6 long long ans;
 7 inline int Abs(const int &x){return x<0 ? -x : x;}
 8 inline void AddEdge(const int &U,const int &V,const int &W)
 9 {v[++en]=V;w[en]=W;next[en]=first[U];first[U]=en;}
10 int n,a,b,c,res;
11 char C;
12 inline int Get()
13 {
14     res=0;C='*';
15     while(C<'0'||C>'9')C=getchar();
16     while(C>='0'&&C<='9'){res=res*10+(C-'0');C=getchar();}
17     return res;
18 }
19 void dfs(int cur)
20 {
21     vis[cur]=true;
22     sz[cur]=1;
23     for(int i=first[cur];i;i=next[i])
24       if(!vis[v[i]]){dfs(v[i]);sz[cur]+=sz[v[i]];}
25     vis[cur]=false;
26 }
27 void dfs2(int cur)
28 {
29     vis[cur]=true;
30     for(int i=first[cur];i;i=next[i])
31       if(!vis[v[i]])
32         {
33           ans+=(long long)Abs((sz[v[i]]<<1)-n)*w[i];
34           dfs2(v[i]);
35         }
36     vis[cur]=false;
37 }
38 int main()
39 {
40     n=Get();
41     for(int i=1;i<n;i++){a=Get();b=Get();c=Get();AddEdge(a,b,c);AddEdge(b,a,c);}
42     dfs(1);
43     dfs2(1);
44     cout<<ans<<endl;
45     return 0;
46 }

 

相关文章:

  • 2022-12-23
  • 2021-08-03
  • 2022-02-28
  • 2021-08-28
  • 2021-11-09
  • 2021-10-17
  • 2021-07-12
  • 2021-10-10
猜你喜欢
  • 2021-10-16
  • 2022-02-03
  • 2022-01-11
  • 2022-12-23
  • 2021-08-22
  • 2022-01-20
  • 2022-02-18
相关资源
相似解决方案