假设前序序列为pre,后序序列为post,他们的长度分别为n,必有:
pre[0]==post[n-1],同时pre[1]为根节点的第一颗子树的根节点,再post中查找pre[1],这样就可以判定出该树的第一颗子树的前序序列和后序序列。同样的道理,可以判断出该树的所有子树的前序和后序序列。递归解之。代码如下:
#include
<
iostream
>
#include < string >
using namespace std;
long process( int m, string pre, string post)
{
if (pre.substr( 0 , 1 ) != post.substr(post.length() - 1 , 1 ))
return 0 ;
if (pre.length() == 1 )
return 1 ;
long ans = 1 ;
pre = pre.substr( 1 , pre.length());
post = post.substr( 0 , post.length() - 1 );
int numchild = 0 ;
long comb = 1 ;
while (pre.length() > 0 ) {
numchild ++ ;
int index = post.find(pre[ 0 ]);
string newPost = post.substr( 0 , index + 1 );
post = post.substr(index + 1 , post.length());
string newPre = pre.substr( 0 , index + 1 );
pre = pre.substr(index + 1 , pre.length());
ans *= process(m, newPre, newPost);
if (ans == 0 )
return 0 ;
comb = comb * (m - numchild + 1 ) / numchild;
}
return ans * comb;
}
int main()
{
string post, pre;
int m;
cin >> m;
while (m != 0 ) {
cin >> pre >> post;
if (pre.length() != post.length())
cout << 0 << endl;
else
cout << process(m, pre, post) << endl;
cin >> m;
}
}
#include < string >
using namespace std;
long process( int m, string pre, string post)
{
if (pre.substr( 0 , 1 ) != post.substr(post.length() - 1 , 1 ))
return 0 ;
if (pre.length() == 1 )
return 1 ;
long ans = 1 ;
pre = pre.substr( 1 , pre.length());
post = post.substr( 0 , post.length() - 1 );
int numchild = 0 ;
long comb = 1 ;
while (pre.length() > 0 ) {
numchild ++ ;
int index = post.find(pre[ 0 ]);
string newPost = post.substr( 0 , index + 1 );
post = post.substr(index + 1 , post.length());
string newPre = pre.substr( 0 , index + 1 );
pre = pre.substr(index + 1 , pre.length());
ans *= process(m, newPre, newPost);
if (ans == 0 )
return 0 ;
comb = comb * (m - numchild + 1 ) / numchild;
}
return ans * comb;
}
int main()
{
string post, pre;
int m;
cin >> m;
while (m != 0 ) {
cin >> pre >> post;
if (pre.length() != post.length())
cout << 0 << endl;
else
cout << process(m, pre, post) << endl;
cin >> m;
}
}