Codeforces 280C. Game on Tree

题目描述

乍一看每一个点被选它自己而被染色到的概率都是1/n,但仔细想想就会发现,某一个点对答案的贡献只与这个点有多少个祖先有关。

因为如果这个点会被选到,当且仅当它的所有祖先都没有被选到(题目中说会将选到的点所在的整棵子树都染成黑色),所有每个点被选而被染色的概率为1/deep[i]。

又因为每次选的代价为一,所以每个点对答案的贡献就是1/deep[i]。

#include<complex>
#include<cstdio>
using namespace std;
const int N=1e5+7;
struct node{
    int v,nxt;
}e[N<<1];
int n,Enum;
double ans;
int front[N],deep[N];
int qread()
{
    int x=0;
    char ch=getchar();
    while(ch<'0' || ch>'9')ch=getchar();
    while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x;
}
void Insert(int u,int v)
{
    e[++Enum].v=v;
    e[Enum].nxt=front[u];
    front[u]=Enum;
}
void dfs(int x,int from)
{
    for(int i=front[x];i;i=e[i].nxt)
    {
        if(e[i].v==from)continue;
        deep[e[i].v]=deep[x]+1;
        dfs(e[i].v,x);
    }
}
int main()
{
    scanf("%d",&n);
    int u,v;
    for(int i=1;i<n;i++)
    {
        u=qread();v=qread();
        Insert(u,v);Insert(v,u);
    }
    deep[1]=1;
    dfs(1,0);
    for(int i=1;i<=n;i++)
        ans+=1.0/deep[i];
    printf("%.20llf\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/LeTri/p/9157166.html