Description
给你一棵树。
有两种操作:
1.以某个节点为父亲增加一个新节点。
2.计算最大期望深度。
Sample Input
7
1 1
1 1
2 1
1 2
1 3
2 2
2 1
Sample Output
0.750000
0.500000
1.187500
首先有一个性质,对于深度比较深的节点,由于他的值实在太小了,
所以其实是可以不用统计到答案里面去的。。。
然后你就随便选一个深度,我选择的是40。
我们设f[i][j]为以i为子树,最大深度不超过j的概率。
那么计算答案时,直接
∑
j
=
1
(
f
[
x
]
[
j
]
−
f
[
x
]
[
j
−
1
]
)
∗
j
\sum_{j=1}(f[x][j]-f[x][j-1])*j
∑j=1(f[x][j]−f[x][j−1])∗j计算即可。
那么考虑一个点插入所造成的影响。
首先可以得知对于一个f[x][0]他的值为0.5^son[x],son[x]表示儿子个数。
显然他是只会对它上面40层的节点造成影响的,你就一层一层更新即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
int s = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s * f;
}
double f[510000][41];
int fa[510000], son[510000];
double pow_mod(double a, int k) {
double ans = 1.0;
while(k) {
if(k & 1) ans *= a;
a *= a; k /= 2;
} return ans;
}
int main() {
int n = 1;
for(int i = 0; i <= 40; i++) f[n][i] = 1.0;
int Q = read();
for(int i = 1; i <= Q; i++) {
int opt = read(), x = read();
if(opt == 1) {
n++; fa[n] = x;
son[x]++;
for(int i = 0; i <= 40; i++) f[n][i] = 1.0;
double last = f[x][0];
f[x][0] = pow_mod(0.5, son[x]);
for(int i = 1; i <= 40; i++) {
if(x == 1) break;
int u = fa[x];
double hh = f[u][i];
f[u][i] /= (0.5 + 0.5 * last);
f[u][i] *= (0.5 + 0.5 * f[x][i - 1]);
x = u; last = hh;
}
} else {
double ans = 0.0;
for(int i = 1; i <= 40; i++) ans += (double)i * (f[x][i] - f[x][i - 1]);
printf("%.6lf\n", ans);
}
}
return 0;
}