标签:
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.
2 abc cba 2 abc bca 10 abc bca 13 abejkcfghid jkebfghicda
4 1 45 207352860
#include <stdio.h>
#include <string.h>
char
pre[30], post[30];
int
m;
int
find(
char
* p,
char
x) {
int
i=0;
while
(p[i]!=x) i++;
return
i;
}
typedef
long
long
ll;
ll C(
int
a,
int
b) {
ll u = 1;
ll d = 1;
while
(b) {
u *= a--;
d *= b--;
}
return
u/d;
}
ll test(
char
* p,
char
* q,
int
n) {
if
(n==0)
return
1;
ll f = 1;
int
c = 0;
int
i;
while
(n) {
c++;
i = find(q,*p);
f *= test(p+1,q,i);
p += i+1;
q += i+1;
n -= i+1;
}
return
f * C(m,c);
}
int
main() {
while
(
scanf
(
"%d%s%s"
,&m,pre,post)==3) {
printf
(
"%lld\n"
,test(pre+1,post,
strlen
(pre)-1));
}
return
0;
}
标签:
原文地址:http://www.cnblogs.com/Alex0111/p/4622222.html