您的位置:首页 > 其它

Codeforces 280 C. Game on Tree (概率与期望)

2017-06-14 14:44 519 查看

题目描述

传送门

题目大意:给定一棵有根树,每次随机选一个未被删除的点,将以它为根的子树删除。求删除整棵树所用的期望步数。

题解

只有删除掉1号点才算结束。考虑一个点被选中删除的概率。

P(i)=1dep[i],dep[i]表示i点的深度,其中1号根节点的深度为1.

只有他到根路径上的点都没有被选中,他才能被选中。

期望步数实际上就是选中的点的期望次数。

所以E(步数)=∑ni=1P(i)=∑ni=11dep[i]

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 200003
using namespace std;
int n,tot,point
,nxt
,v
,dep
;
void add(int x,int y)
{
tot++; nxt[tot]=point[x]; point[x]=tot; v[tot]=y;
tot++; nxt[tot]=point[y]; point[y]=tot; v[tot]=x;
}
void dfs(int x,int fa)
{
dep[x]=dep[fa]+1;
for (int i=point[x];i;i=nxt[i]){
if (v[i]==fa) continue;
dfs(v[i],x);
}
}
int main()
{
freopen("a.in","r",stdin);
scanf("%d",&n);
for (int i=1;i<n;i++) {
int x,y; scanf("%d%d",&x,&y);
add(x,y);
}
dfs(1,0);
double ans=0;
for (int i=1;i<=n;i++)
ans+=(double)(1.0/dep[i]);
printf("%.9lf\n",ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  概率与期望