【hdu 2376】Average distance
【题目链接】:http://acm.hdu.edu.cn/showproblem.php?pid=2376
【题意】
让你计算树上任意两点之间的距离的和.
【题解】
算出每条边的两端有多少个节点设为num1和num2;
这条边的边权为w;
答案累加上w*num1*num2;
然后总的答案除n*(n-1)/2;
【完整代码】
#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%lld",&x)
#define ref(x) scanf("%lf",&x)
typedef pair<int, int> pii;
typedef pair<LL, LL> pll;
const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
const double pi = acos(-1.0);
const int N = 1e4+100;
int n;
LL sum[N];
double ans;
vector <int> G[N];
vector <LL> w[N];
void in()
{
rei(n);
rep1(i, 1, n)
G[i].clear(), w[i].clear();
rep1(i, 1, n - 1)
{
int x, y; LL z;
rei(x), rei(y), rel(z);
x++, y++;
G[x].push_back(y),G[y].push_back(x);
w[x].push_back(z), w[y].push_back(z);
}
}
void dfs(int x, int fa)
{
sum[x] = 1;
int len = G[x].size();
rep1(i,0,len-1)
{
int y = G[x][i];
if (y == fa) continue;
dfs(y, x);
sum[x] += sum[y];
ans += 1LL*(n - sum[y])*sum[y] * w[x][i];
}
}
void o()
{
double tt = n*(n - 1) / 2;
ans /= tt;
printf("%.8f\n", ans);
}
int main()
{
//freopen("F:\\rush.txt", "r", stdin);
int t;
rei(t);
while (t--)
{
ans = 0;
in();
dfs(1, 0);
o();
}
//printf("\n%.2lf sec \n", (double)clock() / CLOCKS_PER_SEC);
return 0;
}