2-3 Trees
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
Output
Sample Input
6 1000000000 7 1000000000
Sample Output
2 3
题意:一棵树中每个节点都会有两个或三个子节点,给你n个叶子节点,要求叶子节点的深度相同,问有多少种树的方式,异构的算多种。
思路:dp[k][n]表示以n个叶子节点组成深度为k的树的形式有多少种,然后递推即可。我这里用到了滚动数组,其实不用也可以。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
ll dp[2][10010],MOD,f[10010],ans;
int n,pow2[15],pow3[15];
int main()
{
int t=0,i,j,k,a,b,l,r,l_1,r_1,l_2,r_2,L,R;
pow2[1]=1;
pow3[1]=1;
for(i=2;i<=13;i++)
{
pow2[i]=pow2[i-1]*2;
pow3[i]=pow3[i-1]*3;
}
while(~scanf("%d%lld",&n,&MOD))
{
if(n==1)
{
printf("%lld\n",1%MOD);
continue;
}
memset(dp,0,sizeof(dp));
dp[0][1]=1;
t=1;
ans=0;
while(pow2[t+1]<=n)
{
t++;
if(t&1)
{
a=1;b=0;
}
else
{
a=0;b=1;
}
memset(dp[b],0,sizeof(dp[b]));
memset(f,0,sizeof(f));
L=pow2[t];
R=min(pow3[t],n);
for(i=L;i<=R;i++)
for(j=pow2[t-1];j<=i-pow2[t-1];j++)
{
f[i]=(f[i]+dp[a][j]*dp[a][i-j])%MOD;
}
for(i=L;i<=R;i++)
dp[b][i]=f[i];
for(i=L;i<=R;i++)
for(j=pow2[t-1]*2;j<=i-pow2[t-1];j++)
{
dp[b][i]=(dp[b][i]+f[j]*dp[a][i-j])%MOD;
}
ans=(ans+dp[b][n])%MOD;
}
printf("%lld\n",ans);
}
}