题意:给出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;
}