求i点的遍历位置的概率公式
因为 从祖先到i点的一条线上的所有点都要遍历,其余途中经过的各个点的分枝(除了这条直线)都有两种选择可选可不选
所以概率公式为 deepi+sum[i]/2.0(这个点以上的除了祖先到这个点的线分支上点的数量)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#define LL long long
using namespace std;
struct tree{
LL sonAm,id;
tree(){};
tree(LL a,LL b):sonAm(a),id(b){};
};
vector<tree>ve[110000];
LL am[110000],deep[110000],n;
LL dfs1(int pre)
{
if(ve[pre].size()==0)return 1;
LL sum = 0;
for(int i=0;i<ve[pre].size();i++)
{
ve[pre][i].sonAm+=dfs1(ve[pre][i].id);
sum+=ve[pre][i].sonAm;
}
return sum+1;
}
void dfs2(LL pre,LL sum,LL pre2)
{
deep[pre] = sum;
am[pre]+=pre2;
LL sum1 = 0;
for(int i=0;i<ve[pre].size();i++) sum1+=ve[pre][i].sonAm;
for(int i=0;i<ve[pre].size();i++)
dfs2(ve[pre][i].id,sum+1,pre2+sum1-ve[pre][i].sonAm);
}
int main()
{
scanf("%I64d",&n);
for(int i=2;i<=n;i++)
{
LL pre;
scanf("%I64d",&pre);
ve[pre].push_back(tree(0,i));
}
LL test = dfs1(1);
dfs2(1ll,1ll,0ll);
for(int i=1;i<=n;i++)
printf("%f ",deep[i]+am[i]/2.0);
return 0;
}