poj 1240 Pre-Post-erous!(递归+组合计数)
Time Limit: 1000ms Memory Limit: 65536kB
Description
We are all familiar with pre-order, in-order and post-order traversals of binary trees. A common problem in data structure classes is to find the pre-order traversal of a binary tree when given the in-order and post-order traversals. Alternatively, you can find the post-order traversal when given the in-order and pre-order. However, in general you cannot determine the in-order traversal of a tree when given its pre-order and post-order traversals. Consider the four binary trees below:
a a
a a
/ /
\ \
b b
b b
/
\ /
\
c
c c
c
All of these trees have the same pre-order and post-order traversals. This phenomenon is not restricted to binary trees, but holds for general m-ary trees as well.
Input
Input will consist of multiple problem instances. Each instance will consist of a line of the form
m s1 s2
indicating that the trees are m-ary trees, s1 is the pre-order traversal and s2 is the post-order traversal.All traversal strings will consist of lowercase alphabetic characters. For all input instances, 1 <= m <= 20 and the length of s1 and s2 will be between 1 and 26 inclusive. If the length of s1 is k (which is the same as the length of s2, of course), the first k letters of the alphabet will be used in the strings. An input line of 0 will terminate the input.
Output
For each problem instance, you should output one line containing the number of possible trees which would result in the pre-order and post-order traversals for the instance. All output values will be within the range of a 32-bit signed integer. For each problem instance, you are guaranteed that there is at least one tree with the given pre-order and post-order traversals.
Sample Input
2 abc cba
2 abc bca
10 abc bca
13 abejkcfghid jkebfghicda
0
Sample Output
4
1
45
207352860
Source
East Central North America 2002
递归,已知一个先序和后序序列后通过先序可以找到根节点,去掉根结点后根据先序求出第一个子树的根,再从后序中找到这个根,进而确定第一个子树的先序后序序列,递归求解其种类,最后将每一子树种类求积,并考虑m叉树一层有i个子树时候该层安排方法为C(m,i),再与子树种类求积极为答案方法种数。做这个题目时候找一棵稍微复杂的树算一算大概可以看出递归方法。
Accepted 140kB 1ms 615 B G++
#include<stdio.h>
#include<string.h>
char s1[27],s2[27];
int m,len;
int C(int a,int b)
{
long long int ans=1;
for (int i=a;i>=a-b+1;i--)
ans*=i;
for (int i=b;i>=1;i--)
ans/=i;
return (int)ans;
}
int f(int m,int l,char *s1,char* s2)
{
if (l==0)
return 1;
int now=0,count=0,ans=1;
while (now<l)
{
for (int i=now;i<l;i++)
if (s2[i]==s1[now])
{
count++;
ans*=f(m,i-now,s1+now+1,s2+now);
now=i+1;
break;
}
}
return ans*C(m,count);
}
int main()
{
while (scanf("%d",&m)&&m)
{
scanf(" %s %s\n",s1,s2);
len=strlen(s1);
printf("%d\n",f(m,len-1,s1+1,s2));
}
return 0;
}