Tree dp
Title: https: //nanti.jisuanke.com/t/41403
Total (sum of the distances of the original) three requirements result of the mold 3 and the distance between any two points: the meaning of the questions
#include <bits / STDC ++ H.> the using namespace STD; #define Pb push_back typedef Long Long LL; const int M = 1E4 + . 4 ; const int MOD = 1E9 + . 7 ; struct Node { int V; LL W; }; LL C [ M] [ . 3 ], S [M] [ . 3 ], ANS [M]; // C [i] [j]: i is expressed in the root, and the path after the consumption of the modulo number j of path // S [ i] [j]: i is expressed in root, after consumption of the path to the path j modulo the total consumed Vector <Node> E [M] ;; void DFS ( int U, int f,ll pre){ C[u][0]=C[u][1]=C[u][2]=0; S[u][0]=S[u][1]=S[u][2]=0; int len=e[u].size(); for(int i=0;i<e[u].size();i++){ int v=e[u][i].v; if(v==f) continue; dfs(v,u,e[u][i].w); //算跨越跟节点的贡献 for(int p=0;p<3;p++){ for(int j=0;j<3;j++) for(int k=0;k<3;k++) if(p==(j+k)%3) ans[p]=(ans[p]+S[u][j]*C[v][k]%mod+C[u][j]*S[v][k]%mod)%mod; } for(int j=0;j<3;j++){ C[u][j]=(C[u][j]+C[v][j])%mod; S[u][j]= (S [u] [J] + S [V] [J])% MOD; } } for ( int I = 0 ; I < . 3 ; I ++) // count of u as with the contribution of the answer, directly u each subtree count contribution ANS [I] = (ANS [I] + S [u] [I])% MOD; LL C [ . 3 ], S [ . 3 ]; Memset (C, 0LL, the sizeof ( C)); Memset (S, 0LL, the sizeof (S)); for ( int I = 0 ; I < . 3 ; I ++ ) { int T = (I pre-% . 3 + . 3 )% . 3 ; C [I]=(c[i]+C[u][t])%mod; s[i]=(s[i]+(S[u][t]+C[u][t]*pre%mod)%mod)%mod; } if(f!=0) c[pre%3]=(c[pre%3]+1ll)%mod,s[pre%3]=(s[pre%3]+pre)%mod; for(int i=0;i<3;i++) C[u][i]=c[i],S[u][i]=s[i]; } int main(){ int n; while(~scanf("%d",&n)){ for(int i=0;i<=n;i++) e[i].clear(); memset(S,0,sizeof(S)); memset(C,0,sizeof(C)); for(int i=1;i<n;i++){ int u,v; ll w; for(int i=0;i<3;i++) ans[i]=0ll; scanf("%d%d%lld",&u,&v,&w); u++,v++; e[u].pb(node{v,w}); e[v].pb(node{u,w}); } dfs(1,0,0); printf("%lld %lld %lld\n",ans[0]*2ll%mod,ans[1]*2ll%mod,ans[2]*2ll%mod); } return 0;; }