题目:
http://codeforces.com/problemset/problem/500/D
题意:
n个点,n-1条边的树,有边权值。
任意选出三个点建城市,其花费是dis(a,b)+ dis(a,c)+ dis(b,c);
有q个询问,每次改变一条边的长度,求出所有建城市的方案的花费期望。
思路:
dfs:求出v点子树的节点个数,求出(u,v)边对总路径的贡献。在未改变路径之前的期望值是 sum/ C(n,3).
在q个询问中,算出改变的长度与原来的长度的差值贡献,用原来的答案进行计算即可。
AC.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e5+10;
int u[maxn], v[maxn], w[maxn];
double sum;
int n;
int tot, head[maxn];
struct Edge {
int to, w, next;
}edge[maxn*2];
void addedge(int u, int v, int w)
{
edge[tot].to = v;
edge[tot].w = w;
edge[tot].next = head[u];
head[u] = tot++;
}
int f[maxn], num[maxn];
int dfs(int u, int fa)
{
int son = 1;
f[u] = fa;
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to, w = edge[i].w;
if(v == fa) continue;
int x = dfs(v, u);
int y = n-x;
double c = (double)x*(x-1)*y + (double)y*(y-1)*x;
sum += c*w;
son += x;
}
num[u] = son;
return num[u];
}
void init()
{
tot = 0;
memset(head, -1, sizeof(head));
memset(num, 0, sizeof(num));
}
int main()
{
//freopen("in", "r", stdin);
while(~scanf("%d", &n)) {
init();
for(int i = 1; i < n; ++i) {
scanf("%d%d%d", &u[i], &v[i], &w[i]);
addedge(u[i], v[i], w[i]);
addedge(v[i], u[i], w[i]);
}
sum = 0;
dfs(1, -1);
double c = (double)n*(n-1)*(n-2)/6.0;
int q;
scanf("%d", &q);
while(q--) {
int id, r, x, y;
scanf("%d%d", &id, &r);
int cnt = w[id] - r;
w[id] = r;
if(f[u[id]] == v[id]) x = num[u[id]];
else x = num[v[id]];
y = n-x;
double tim = (double)x*(x-1)*y + (double)y*(y-1)*x;
sum -= tim*cnt;
printf("%.10f\n", sum/c);
}
}
return 0;
}