zoukankan      html  css  js  c++  java
  • Codeforces 643E Bear and Destroying Subtrees 树形dp (看题解)

    Bear and Destroying Subtrees

    我们先考虑没有修改的到从根开始的最长期望深度。

    dp[ i ][ j ] 表示 i 这棵子树所有的边有一半概率存在的情况下, 最长深度为 j 的概率。

    我们只用考虑50层就够了, 因为概率随长度比边长成指数级减少。 这样的话,处理出一个 dp的前缀之后,

    转移可以一个一个地合到根上, 但是我们是一个一个往里面加点, 需要暴力地网上爬去更新dp值, 这个

    状态很难取O(1)地更新。。。

    我们考虑新的dp状态dp[ i ][ j ] 表示在 i 这棵子树中, 最大深度 <= j 的概率。 把状态转移方程写出来就可以

    发现可以O(1)修改啦。

    这种暴力往上更新的尽量要化成每个子树可以分开的形式。

    #include<bits/stdc++.h>
    #define LL long long
    #define LD long double
    #define ull unsigned long long
    #define fi first
    #define se second
    #define mk make_pair
    #define PLL pair<LL, LL>
    #define PLI pair<LL, int>
    #define PII pair<int, int>
    #define SZ(x) ((int)x.size())
    #define ALL(x) (x).begin(), (x).end()
    #define fio ios::sync_with_stdio(false); cin.tie(0);
    
    using namespace std;
    
    const int N = 5e5 + 7;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int mod = 1e9 + 7;
    const double eps = 1e-8;
    const double PI = acos(-1);
    
    template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;}
    template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;}
    template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;}
    template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;}
    
    int n, q, pa[N];
    int depth[N];
    double dp[N][51];
    
    int main() {
        for(int i = 1; i < N; i++)
            for(int j = 0; j <= 50; j++)
                dp[i][j] = 1.0;
        scanf("%d", &q); n++;
        while(q--) {
            int op, u;
            scanf("%d%d", &op, &u);
            if(op == 1) {
                int v = ++n;
                pa[v] = u;
                int cur = u;
                double tmp1 = dp[cur][0] * 0.5 + 0.5, tmp2;
                for(int o = 1; o < 50 && pa[cur]; o++) {
                    tmp2 = dp[pa[cur]][o] * 0.5 + 0.5;
                    dp[pa[cur]][o] /= tmp1;
                    cur = pa[cur];
                    tmp1 = tmp2;
                }
                dp[u][0] *= 0.5;
                cur = u;
                for(int o = 1; o <= 50 && pa[cur]; o++) {
                    dp[pa[cur]][o] *= 0.5 + 0.5 * dp[cur][o - 1];
                    cur = pa[cur];
                }
            } else {
                double ans = depth[u];
                for(int i = 1; i <= 50; i++)
                    ans += i * (dp[u][i] - dp[u][i - 1]);
                printf("%.12f
    ", ans);
            }
        }
        return 0;
    }
    
    /*
    */
  • 相关阅读:
    内部共享上网
    Harbor部署
    一、Gitlab安装
    Dockerfile
    DockerCompose
    二、Git
    nginx域名代理
    三、jenkins持续集成工具安装
    chrome对于“submit”关键字的保留
    insightface 提取人脸特征(超简洁)
  • 原文地址:https://www.cnblogs.com/CJLHY/p/10936763.html
Copyright © 2011-2022 走看看