ACdream 1412 2-3 Trees 递推

题目描述:

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

题目分析:

求一个含有n个叶子节点的2-3Tree(这种树除了叶子节点外 每个结点都有且仅有2或3个孩子),有多少种形态?
因为我们知道最底层(叶子节点)的个数,所以我们可以向上推导,这n个叶子能组成多少个2孩子父节点和3孩子父节点,一层一层向上推导。同时每一层的2子父节点与3子父节点的排列也是造成形态多样的原因。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>

const int MAXN=5010;
typedef long long LL;
using namespace std;

LL C[MAXN/2][MAXN/2];
int n,mod;
LL dp[MAXN];

void getC()//排列数
{
    C[0][0]=1;
    C[1][0]=C[1][1]=1;
    for(int i=2; i<=n/2; i++)
    {
        C[i][0]=1;C[i][i]=1;
        for(int j=1; j<i; j++)
        {
            C[i][j]=(C[i-1][j]%mod+C[i-1][j-1]%mod)%mod;
        }
    }
}

LL DP(int n)
{
    if (dp[n]) return dp[n];
    for(int i=0; i<=n/2; i++)//2子父节点个数
    {
        if ((n-i*2)%3==0)//3子父节点个数
        {
            int j=(n-i*2)/3;
            dp[n]=(dp[n]+DP(i+j)*C[i+j][j])%mod;
        }
    }
    return dp[n]%mod;
}

int main()
{
    while(scanf("%d%d",&n,&mod)!=-1)
    {
        getC();
        memset(dp,0,sizeof(dp));
        dp[1]=1;dp[2]=1;dp[3]=1;
        printf("%lld\n",DP(n));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值