ACdreamoj 1412 dp

http://115.28.76.232/problem?pid=1412

Problem Description

      2-3 tree is an elegant data structure invented by John Hopcroft. It is designed to implement the same functionality as the binary search tree. 2-3 tree is an ordered rooted tree with the following properties:

  • the root and each internal vertex have either 2 or 3 children;
  • the distance from the root to any leaf of the tree is the same.

      The only exception is the tree that contains exactly one vertex — in this case the root of the tree is the only vertex, and it is simultaneously a leaf, i.e. has no children. The main idea of the described properties is that the tree with l leaves has the height O(log l).
      Given the number of leaves l there can be several valid 2-3 trees that have l leaves. For example, the picture below shows the two possible 2-3 trees with exactly 6 leaves.


      Given l find the number of different 2-3 trees that have l leaves. Since this number can be quite large, output it modulo r.

Input
      Input file contains two integer numbers: l and r (1 ≤ l ≤ 5 000, 1 ≤ r ≤ 10 9).
Output
      Output one number — the number of different 2-3 trees with exactly l leaves modulo r.
Sample Input
6 1000000000
7 1000000000
Sample Output
2
3
PS:有了正确的思路,还要有一定的实现能力,

//时间O(n*n)
#include <stdio.h>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#define maxn 5005
#define eps 1e-10
#define LL long long

using namespace std;

int n,mod,c[2505][2505];
void init()
{
    for(int i=1; i<=2500; i++)
    {
        c[0][i]=c[i][i]=1;
    }
    for(int i=2; i<=2500; i++)
    {
        for(int j=1; j<=i/2; j++)
        {
            c[i-j][i]=(c[j][i-1]+c[j-1][i-1])%mod;
            c[j][i]=c[i-j][i];
        }
    }
}
LL dp[15][maxn],minn,maxx;
int main()
{
    while(~scanf("%d%d",&n,&mod))
    {
        init();
        memset(dp,0,sizeof(dp));
        dp[0][1]=minn=maxx=1LL;
        for(int k=1;k<15;k++)//树的深度
        {
             if(minn*2>n) break;
             for(int i=minn;i<=maxx;i++)//上一层的最小和最大的节点数
                for(int j=i*2;j<=i*3&&j<=n;j++)//由上一层推下一层
                {
                     dp[k][j]+=dp[k-1][i]*c[i*3-j][i];
                     dp[k][j]%=mod;
                }
            minn*=2;
            maxx*=3;
            maxx=maxx<n?maxx:n;
        }
        int ans=0;
        for(int i=0;i<15;i++)
              ans=(ans+dp[i][n])%mod;
        printf("%d\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值