Pre-Post-erous! POJ - 1240 (已知前序和后序遍历求原来树的种类)

传送门

题意:给出k叉树的前序和后序遍历序列,问一共有多少种这样的k叉树

题解:大方向:递归+组合数

对于k叉树的前序和后序遍历序列,第一个字符一定表示这棵k叉树的根,在后序遍历序列中最后一个字符表示k叉树的根。前序遍历序列中的第二个字符x1一定是k叉树根节点的第一棵子树的根节点,那么在后序遍历中,从开始到x1的部分一定是k叉树的第一颗子树的后序遍历序列,将这部分截下来,若第一颗子树的节点个数为n1,那么在前序遍历序列中去掉根节点,再从头截掉n1个字符,这n1个字符一定是k叉树第一颗子树的前序遍历序列。。。。就这样递归操作,可以知道每层有多少个节点,再跟据占位法,利用组合数求出答案。

附上代码:


#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>

using namespace std;

const int maxn=35;

char pre[maxn];
char post[maxn];

vector<int>branch;

void branch_count(int pr1,int pr2,int po1,int po2)
{
    if(pr1==pr2&&po1==po2){
        return ;
    }else{
        int a,b,len,branchcnt=0;
        a=pr1+1;
        b=po1;
        len=0;
        while(b<po2){
            while((pre[a]!=post[b+len])&&(b+len<=po2)){
                len++;
            }
            branchcnt++;
            branch_count(a,a+len,b,b+len);
            a=a+len+1;
            b=b+len+1;
            len=0;
        }
        branch.push_back(branchcnt);
    }
}

int cal(int n,int m)
{
    int a=n-m+1,ans=1;
    for(int i=1;i<=m;i++){
        ans*=a++;
        ans/=i;
    }
    return ans;
}

int main()
{
    int m;
    while(scanf("%d",&m)!=EOF&&m){
        scanf("%s%s",pre,post);
        int len=strlen(pre);
        branch_count(0,len-1,0,len-1);
        int ans=1;
        int len2=branch.size();
        for(int i=0;i<len2;i++){
            ans*=cal(m,branch[i]);
        }
        printf("%d\n",ans);
        branch.clear();
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值