题目描述
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: 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 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.
输出描述:
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.
示例1
输入
2 abc cba 2 abc bca 10 abc bca 13 abejkcfghid jkebfghicda
输出
4 1 45 207352860
题目链接:Pre-Post
参考资料:大佬链接
最终AC代码:
#include <bits/stdc++.h>
using namespace std;
int m;
int C(int n, int m){
int cnt=1;
for(int i=1; i<=n; i++) cnt= cnt * (m - i + 1) / i; //刚好累计的cnt可以整除递增的i故采用int
return cnt;
}
int getAns(char *pre, char *post, int len){
if(len == 1) return 1;
int i, j, n=0, cnt=1;
for(i=1, j=0; i<len; i=j+2){
for( ; j<len; j++) if(pre[i] == post[j]) break;
cnt *= getAns(pre+i, post+i-1, j-i+2); //注意这里递归访问时 第二项参数是post+i-1 而不是post
n++;
}
return cnt*C(n, m);
}
int main(){
char pre[25], post[25];
while(~scanf("%d %s %s", &m, pre, post)){
printf("%d
", getAns(pre, post, strlen(pre)));
}
return 0;
}
总结:目前还不是完全理解这个题目,详细的分析可见牛客网评论区。先将本题记录下来,用以日后复习巩固时用。等到之后有了新的感悟,再来更新本题总结。