POJ 1240 Pre-Post-erous!(组合数学+递归)

190 篇文章 1 订阅
18 篇文章 0 订阅

Description
给出一棵m-叉树的前序和后序遍历序列,问这棵树有多少种
Input
多组用例,每组用例首先输入一个整数m表示树的叉数,之后为两个串表示该树的前序和后序遍历序列,以m=0结束输入
Output
对于每组用例,输出满足输入的前序和后序遍历序列的m-叉树的个数
Sample Input
2 abc cba
2 abc bca
10 abc bca
13 abejkcfghid jkebfghicda
0
Sample Output
4
1
45
207352860
Solution
根据前序遍历序列和后序遍历序列递归构造这棵树,递归过程中统计每个节点的儿子节点个数cnt,那么ans*=C(m,cnt)
Code

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
#define maxn 33
int m,id[maxn],ans;
char pre[maxn],post[maxn];
int C(int a,int b)
{
    int ans=1;
    for(int i=1;i<=a-b;i++)
        ans=ans*(b+i)/i;
    return ans;
}
void count(int a,int b,int c,int d)
{
    if(a>b)return ;
    int cnt=0;
    a++;
    int k=id[pre[a]-'a'];
    while(c<d)
    {
        cnt++;
        int l=k-c;
        count(a,a+l,c,k);
        c=k+1,a=a+l+1;
        k=id[pre[a]-'a'];
    }
    ans*=C(m,cnt);
}
int main()
{
    while(~scanf("%d",&m),m)
    {
        scanf("%s%s",pre,post);
        int len=strlen(pre);
        for(int i=0;i<len;i++)
            id[post[i]-'a']=i;
        ans=1;
        count(0,len-1,0,len-1);
        printf("%d\n",ans);
    }
    return 0;
} 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值