zoukankan      html  css  js  c++  java
  • BZOJ5305 HAOI2018苹果树(概率期望+动态规划)

      每种父亲编号小于儿子编号的有标号二叉树的出现概率是相同的,问题相当于求所有n个点的此种树的所有结点两两距离之和。

      设f[n]为答案,g[n]为所有此种树所有结点的深度之和,h[n]为此种树的个数。

      枚举左右子树大小,则有f[n]=Σ{[f[i]+(g[i]+h[i]*i)·(n-i)]·h[n-i-1]+[f[n-i-1]+(g[n-i-1]+h[n-i-1]*(n-i-1))·(i+1)]·h[i]}·C(n-1,i),即对两棵子树分别统计贡献,C(n-1,i)即给左右子树分配编号。g[n]=Σ[(g[i]+h[i]*i)·h[n-i-1]+(g[n-i-1]+h[n-i-1]*(n-i-1))·h[i]]·C(n-1,i),h[n]=Σh[i]·h[n-i-1]·C(n-1,i),比较显然。

    #include<iostream> 
    #include<cstdio>
    #include<cmath>
    #include<cstdlib>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    #define ll long long
    #define N 2010
    char getc(){char c=getchar();while ((c<'A'||c>'Z')&&(c<'a'||c>'z')&&(c<'0'||c>'9')) c=getchar();return c;}
    int gcd(int n,int m){return m==0?n:gcd(m,n%m);}
    int read()
    {
        int x=0,f=1;char c=getchar();
        while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
        while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
        return x*f;
    }
    int n,P,C[N][N],f[N],g[N],h[N];
    void inc(int &x,int y){x+=y;if (x>=P) x-=P;}
    int main()
    {
    #ifndef ONLINE_JUDGE
        freopen("bzoj5305.in","r",stdin);
        freopen("bzoj5305.out","w",stdout);
        const char LL[]="%I64d
    ";
    #else
        const char LL[]="%lld
    ";
    #endif
        n=read(),P=read();
        C[0][0]=1;
        for (int i=1;i<=n;i++)
        {
            C[i][0]=C[i][i]=1;
            for (int j=1;j<i;j++) 
            C[i][j]=(C[i-1][j-1]+C[i-1][j])%P;
        }
        f[0]=g[0]=0;h[0]=1;
        for (int i=1;i<=n;i++)
        {
            for (int j=0;j<i;j++)
            inc(h[i],1ll*h[j]*h[i-j-1]%P*C[i-1][j]%P);
            for (int j=0;j<i;j++)
            inc(g[i],((g[j]+1ll*j*h[j])%P*h[i-j-1]+(g[i-j-1]+1ll*(i-j-1)*h[i-j-1])%P*h[j])%P*C[i-1][j]%P);
            for (int j=0;j<i;j++)
            inc(f[i],((f[j]+(g[j]+1ll*j*h[j])%P*(i-j))%P*h[i-j-1]+(f[i-j-1]+(g[i-j-1]+1ll*(i-j-1)*h[i-j-1])%P*(j+1))%P*h[j])%P*C[i-1][j]%P);
        }
        cout<<f[n];
        return 0;
    }
  • 相关阅读:
    Flask 框架下 Jinja2 模板引擎高层 API 类——Environment
    java中的URLEncoder.encode对应JS中用decodeURIComponent,js和java编码,解码
    SQL触发器(AFTER和INSTEAD OF)
    jquery对中文进行base64加密,后台用java进行base64解密
    org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [WebApp] in context with path关于数据库库的问题
    Mybatis-Plus代码生成器
    Swagger2-注解说明
    Maven详细配置
    JDK环境变量配置
    内存泄漏测试
  • 原文地址:https://www.cnblogs.com/Gloid/p/10087167.html
Copyright © 2011-2022 走看看