HDU 2376(树上任意2点间的距离)

来源:互联网 发布:美剧学口语 知乎 编辑:程序博客网 时间:2024/05/22 09:48

题目链接
题意:求树上任意2点之间距离的期望
dfs跑一遍,统计每条边的贡献

#include<bits/stdc++.h>using namespace std;#define cl(a,b) memset(a,b,sizeof(a))#define LL long longconst int maxn = 11005;const int inf  = 1 << 23;struct Edge{    int to ,w;    Edge(){}    Edge(int a,int b){        to=a;        w=b;    }};int n;vector<Edge> G[maxn];LL sum[maxn];double ret = 0;void dfs(int x,int fa){    sum[x]=1;    for(int i=0;i<G[x].size();i++){        int y = G[x][i].to;        int w = G[x][i].w;        if(y==fa)continue;        dfs(y,x);        sum[x]+=sum[y];        ret+= sum[y]*(n-sum[y])*w;    }}int main(){    int T;scanf("%d",&T);    while(T--){        for(int i=0;i<maxn;i++)G[i].clear();        scanf("%d",&n);        for(int i=0;i<n-1;i++){            int x,y,z;            scanf("%d%d%d",&x,&y,&z);            G[x].push_back(Edge(y,z));            G[y].push_back(Edge(x,z));        }        cl(sum,0);        ret = 0;        dfs(0,-1);        printf("%.10lf\n",ret/(n-1)/n*2);    }    return 0;}
0 0