Codeforces 280C Game on Tree 树形期望dp

41 篇文章 0 订阅
31 篇文章 1 订阅

题目链接


题意:

给出一棵树,每次可以拆掉一颗子树,问拆完整棵树次数的期望。


思路:

删掉x点,将x点的贡献记为1,将x的后辈结点贡献记为0。
换句话说如果x点是作为根结点删掉的那么贡献为1,否则贡献为0。
现在的问题就是求 f(i)=p(i)1+(1p(i))0
其中 p(i)=1/depth(i)


#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<iomanip>
using namespace std;

#define all(x) (x).begin(), (x).end()
#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)
#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)
#define mes(a,x,s)  memset(a,x,(s)*sizeof a[0])
#define mem(a,x)  memset(a,x,sizeof a)
#define ysk(x)  (1<<(x))
typedef long long ll;
typedef pair<int, int> pii;
const int INF =0x3f3f3f3f;
const int maxn= 100000   ;
int n;
vector<int >G[maxn+10];

double ans;

void dfs(int x,int fa,int depth)
{
    ans+=1.0/depth;
    int siz=G[x].size();
    for0(i,siz)
    {
        int y=G[x][i];if(y==fa) continue;
        dfs(y,x,depth+1);
    }
}
int main()
{
   std::ios::sync_with_stdio(false);
   while(cin>>n)
   {
       for1(i,n) G[i].clear();
       int x,y;
       for1(i,n-1)
       {
           cin>>x>>y;
           G[x].push_back(y);
           G[y].push_back(x);
       }
       ans=0;
       dfs(1,-1,1);
       cout<<fixed<<setprecision(20)<<ans<<endl;
   }
   return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值