求树上任意两点间的距离和

题目:给定一棵 N 个点的无向树,边有边权,求树上任意两点间的距离和,答案对 1e9+7 取模。

题解:依题可知,这道题所求即Σi=1n−1Σj=i+1ndist(i,j),枚举树上任意两点并计算距离的复杂度要达到 O(n2logn),时间难以承受。
可以换一种方式思考,由于任意两点的距离都是答案贡献的一部分,因此可以考虑每条边对答案的贡献,将这条边删去后,分成的两棵子树内的点都需要经过这条边才能到达另一棵子树,因此这条边对答案贡献为w[i]∗size[v]∗(n−size[v])。

#include <bits/stdc++.h>
using namespace std;
const int maxn=5010;
const int mod=1e9+7;

inline int read(){
    int x=0,f=1;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    return f*x;
}

struct node{
    int nxt,to,w;
    node(int x=0,int y=0,int z=0):nxt(x),to(y),w(z){}
}e[maxn<<1];
int tot=1,head[maxn];
inline void add_edge(int from,int to,int w){
    e[++tot]=node(head[from],to,w),head[from]=tot;
}

int n,size[maxn];
long long ans;

void dfs(int u,int fa){
    size[u]=1;
    for(int i=head[u];i;i=e[i].nxt){
        int v=e[i].to;if(v==fa)continue;
        dfs(v,u);
        size[u]+=size[v];
    }
}

void read_and_parse(){
    n=read();
    for(int i=1;i<n;i++){
        int from=read(),to=read(),w=read();
        add_edge(from,to,w),add_edge(to,from,w);
    }
    dfs(1,0);
}

void dfs2(int u,int fa){
    for(int i=head[u];i;i=e[i].nxt){
        int v=e[i].to,w=e[i].w;if(v==fa)continue;
        ans=(ans+(long long)w*size[v]*(n-size[v]))%mod;
        dfs2(v,u);
    }
}

void solve(){
    dfs2(1,0);
    printf("%lld
",ans);
}

int main(){
    read_and_parse();
    solve();
    return 0;
}
原文地址:https://www.cnblogs.com/ke-xin/p/13544580.html