传送门:https://odzkskevi.qnssl.com/86ae857f80d3f4ae7389f98461306080?v=1499831299
题意:定义一棵树的价值为:这棵树上所有简单路径的长度之和,现在给出n个节点的树,边的权值为w,
以1为根节点,问所有子树价值的和
题解:树型dp
设dp[u]为以u为根的子树的价值,sz[u]为以u为根的子树的节点数,val[u]为u与所有子节点的距离之和
deep[u]为u的深度,设u为当前节点,v为u的子节点
首先很容易想到val[u]=∑(val[v]+sz[v]*w(u,v))
设tot为val[u]中除去u到子树v的所有节点的距离,即tot=val[u]-(val[v]+sz[v]*w(u,v))
考虑每个子树v对dp[u]的贡献:dp[v]+sz[v]*tot(因为每条路径都可以在子树v中有sz[v]种不同的延伸)
最后得到:dp[u]=∑(dp[v]+sz[v]*tot)+val[u]
因为每个子树会根据自己根节点的深度被重复计算,因此ans=∑deep[u]*dp[u]
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MX = 1e5 + 5;
const LL mod =1e9 + 7;
struct Edge{
int v,nxt;
LL w;
}E[MX*2];
int head[MX],tot;
void init(){
memset(head,-1,sizeof(head));
tot=0;
}
void add(int u,int v,LL w){
E[tot].v=v;
E[tot].w=w;
E[tot].nxt=head[u];
head[u]=tot++;
}
LL dp[MX],sz[MX],val[MX];
int dep[MX];
void DP(int u,int fa,int deep){
dp[u]=0;sz[u]=1;val[u]=0;dep[u]=deep;
for(int i=head[u];~i;i=E[i].nxt){
int v=E[i].v;
LL w=E[i].w;
if(v==fa) continue;
DP(v,u,deep+1);
val[u]=(val[u]+val[v]+sz[v]*w)%mod;
sz[u]+=sz[v];
}
dp[u]=(dp[u]+val[u])%mod;
for(int i=head[u];~i;i=E[i].nxt){
int v=E[i].v;
LL w=E[i].w;
if(v==fa) continue;
LL tot=val[u]-val[v]+mod;
LL cnt=w*sz[v]%mod;
dp[u]=(dp[u]+(tot-cnt+mod)*sz[v])%mod;
}
}
int main(){
int T,n;
//freopen("in.txt","r",stdin);
scanf("%d",&T);
for(int cas=1;cas<=T;cas++){
init();
scanf("%d",&n);
for(int i=1;i<n;i++) {
int u,v;
LL w;
scanf("%d%d%I64d",&u,&v,&w);
add(u,v,w); add(v,u,w);
}
DP(1,-1,1);
LL ans=0;
for(int i=1;i<=n;i++) ans=(ans+dp[i]*dep[i])%mod;
printf("Case %d: %I64d\n",cas,ans);
}
return 0;
}