HDU2376——Average distance(思维+树形DP)

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=2376

原文:https://www.codenong.com/cs109682980/

题意:

给定一棵树,有边权,求树上任意两点之间距离的和的平均值。

思路:

传统求树上两点距离是LCA,任意的话要枚举起点和终点,复杂度\(O(n^2)\)
换个思路,考虑每条边的贡献:****
因为是树,所以任意删除一条边都会将该图分为两个连通块T1,T2,也就是说这条边对答案的贡献就是两个连通块点数的乘积再乘以权值:\(次数=cnt[T1]*cnt[T2]\).
维护每个点的子树所含的点的个数\(num,n-num\)就是另一个连通块的点数

树形dp维护即可。

代码

注意用long long

#pragma GCC optimize(3)
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll>PLL;
typedef pair<int,int>PII;
typedef pair<double,double>PDD;
#define I_int ll
inline ll read()
{<!-- -->
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){<!-- -->if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){<!-- -->x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
char F[200];
inline void out(I_int x) {<!-- -->
    if (x == 0) return (void) (putchar('0'));
    I_int tmp = x > 0 ? x : -x;
    if (x < 0) putchar('-');
    int cnt = 0;
    while (tmp > 0) {<!-- -->
        F[cnt++] = tmp % 10 + '0';
        tmp /= 10;
    }
    while (cnt > 0) putchar(F[--cnt]);
    //cout<<" ";
}
ll ksm(ll a,ll b,ll p){<!-- -->ll res=1;while(b){<!-- -->if(b&1)res=res*a%p;a=a*a%p;b>>=1;}return res;}
const int inf=0x3f3f3f3f,mod=998244353;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int maxn=1e6+100,maxm=3e5+7,N=1e6+7;
const double PI = atan(1.0)*4;
int h[maxn],idx,n;
struct node{<!-- -->
    int e,ne,w;
}edge[maxn*2];
void add(int u,int v,int w){<!-- -->
    edge[idx]={<!-- -->v,h[u],w};h[u]=idx++;
}
ll res=0;
int cnt[maxn];
void dfs(int u,int fa){<!-- -->
    cnt[u]=1;
    for(int i=h[u];~i;i=edge[i].ne){<!-- -->
        int j=edge[i].e,w=edge[i].w;
        if(j==fa) continue;
        dfs(j,u);
        cnt[u]+=cnt[j];
        res=res+(ll)(n-cnt[j])*cnt[j]*w;
    }
}
int main(){<!-- -->
    int T=read();
    while(T--){<!-- -->
        n=read();
        memset(h,-1,sizeof h);idx=0;res=0;
        for(int i=1;i<n;i++){<!-- -->
            int u=read(),v=read(),w=read();
            add(u,v,w);add(v,u,w);
        }
        dfs(1,-1);
        int tt=n*(n-1)/2;
        printf("%.6f\n",(double)res/tt);
    }
    return 0;
}
posted @ 2022-10-20 14:48  kingwzun  阅读(34)  评论(0编辑  收藏  举报