每条边的贡献是边权*一边的点数*另一边的点数。
#include<iostream> #include<cstdio> #include<cstring> #define maxv 20050 #define maxe 40050 using namespace std; struct edge { long long u,v,w,nxt; }e[maxe]; long long n,a,b,c,g[maxv],size[maxv],nume=0,fath[maxv]; void addedge(long long u,long long v,long long w) { e[++nume].u=u; e[nume].v=v; e[nume].w=w; e[nume].nxt=g[u]; g[u]=nume; } void dfs(long long x,long long father) { fath[x]=father;size[x]=1; for (long long i=g[x];i;i=e[i].nxt) { long long v=e[i].v; if (v!=father) { dfs(v,x); size[x]+=size[v]; } } } int main() { scanf("%lld",&n); for (long long i=1;i<=n-1;i++) { scanf("%lld%lld%lld",&a,&b,&c); addedge(a,b,c); addedge(b,a,c); } dfs(1,0); long long ans=0; for (long long i=1;i<=nume;i+=2) { a=e[i].u,b=e[i].v,c=e[i].w; if (fath[a]==b) swap(a,b); ans+=c*size[b]*(n-size[b]); } double now=(double)ans/(n*n-n); printf("%.2lf ",now*2); return 0; }