原文链接:
https://blog.csdn.net/csyifanZhang/article/details/105751387
我的代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define ll long long
ll m;
string prestr,poststr;
ll ans = 1;
ll C(ll a,ll b)
{
if(b==0) return 1;
ll tmp1 = 1; ll tmp2 = 1;
for(int i=1;i<=b;i++){
tmp1 = tmp1*(a-i+1);
tmp2 = tmp2*i;
}
return tmp1/tmp2;
}
ll dfs(string pre,string post){
int len = pre.length();
string str1,str2;
int numtree=0;
pre = pre.erase(0,1);post = post.erase(len-1,1); //去掉首部,去掉末尾
len--;
if(len==0){
return 0;
}
if(pre[0] == post[len-1]){ //只有一颗子树
ll n=0;n=dfs(pre,post);
ans = ans*C(m,n);//cout<<n<<endl;
return 1;
}else{ //多棵子树
while(pre.length()!=0){
for(int i=0;i<pre.length();i++){ //搜寻一棵子树
if(post[i]==pre[0]){
str1 = pre.substr(0,i+1);pre.erase(0,i+1);
str2 = post.substr(0,i+1);post.erase(0,i+1);
ll n=0;n=dfs(str1,str2);//cout<<n<<endl;
ans = ans*C(m,n);//cout<<ans<<endl;
numtree++;break;
}
}
}
return numtree;
}
}
int main()
{
while(cin>>m){
ans = 1;
cin>>prestr>>poststr;
ll n=dfs(prestr,poststr);
ans = ans*C(m,n);
cout<<ans<<endl;
}
}