CF280C Game on Tree 概率与期望

利用期望的线性性,即 $E(a+b)=E(a)+E(b)$. 

对于所有点分别求一下期望然后累加即可. 

code: 

#include <bits/stdc++.h>     
#define N 100006      
using namespace std;  
void setIO(string s) 
{
    string in=s+".in";     
    freopen(in.c_str(),"r",stdin);    
}  
double ans=0.0;   
int edges; 
int hd[N],to[N<<1],nex[N<<1],dep[N];   
void add(int u,int v) 
{
    nex[++edges]=hd[u],hd[u]=edges,to[edges]=v;    
}    
void dfs(int u,int ff) 
{ 
    dep[u]=dep[ff]+1;   
    ans+=1.0/dep[u];    
    for(int i=hd[u];i;i=nex[i]) 
        if(to[i]!=ff) dfs(to[i],u);     
}
int main() 
{
    // setIO("input");             
    int n,i,j;   
    scanf("%d",&n); 
    for(i=1;i<n;++i) 
    {
        int a,b;
        scanf("%d%d",&a,&b); 
        add(a,b),add(b,a);   
    }          
    dfs(1,0);   
    printf("%.6f
",ans);   
    return 0; 
}

  

原文地址:https://www.cnblogs.com/guangheli/p/11771653.html