CF280C-Game on Tree【数学期望】

正题

题目链接:https://www.luogu.com.cn/problem/CF280C


题目大意

(n)个点的一棵树,每次选择一个没有染色的点把它和它的子树染黑,求期望全部染黑的步数。


解题思路

可以理解为我们按照一个顺序轮流染色,如果一个点有祖先节点在它前面就不用计算贡献。

也就是如果一个点要计算贡献的概率就是它要排在所有它的祖先节点前面,也就是(frac{1}{dep_x})。求个和就好了。

时间复杂度(O(n))


code

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N=1e5+10;
int n;double ans;
vector<int> G[N];
void dfs(int x,int fa,int dep){
    for(int i=0;i<G[x].size();i++){
        int y=G[x][i];
        if(y==fa)continue;
        dfs(y,x,dep+1);
    }
    ans+=1.0/(double)dep;
    return;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<n;i++){
        int x,y;
        scanf("%d%d",&x,&y);
        G[x].push_back(y);
        G[y].push_back(x);
    }
    dfs(1,0,1);
    printf("%.10lf
",ans);
}
原文地址:https://www.cnblogs.com/QuantAsk/p/14277873.html