codevs1029

题目地址:http://codevs.cn/problem/1029/

分析:

树的前序遍历,树的中序遍历,树的后序遍历。

代码

#include<iostream>
#include<string>
using namespace std;
string s1,s2;
bool check(string &a,string &b)  //前序可能的左子树与后序可能的左子树是否相配
{
 int i;
 if( a.length()==0 ) 
 { return true;  }
 else
 {
  if (a[0]==b[b.length()-1])
  {
   for (i=1;i<=a.length()-1;i++)
   {
    if( b.find(a[i])>b.length() )  return false; //unfind
   }
         return true;
  }
  else
   return false;
 }
}

int f(string l1,string l2)
{
 int n,m,i;
    string l1l,l1r,l2l,l2r;//l1,l2的左右子树 
 m=0;
 n=l1.length();
 if ((n==0) || (n==1))  //递归结束条件
 { return 1;    }
 else
 {
  for (i= n-1; i>=0; i--)//左子树右子树的可能,i为中间位置
  {
   l1l.assign(l1,2-1,i);
   l1r.assign(l1,i+2-1,n-i-1);


   l2l.assign(l2,1-1,i);
   l2r.assign(l2,i+1-1,n-i-1);


      if( check(l1l,l2l)&& check(l1r,l2r) )
   {   m=m+f(l1l,l2l)*f(l1r,l2r);   }//分步相加,分类相乘
  }
 }
   return m;
}  
 
int main()
{
int x;
  cin>>s1>>s2;
  x=f(s1,s2);
  cout<<x<<endl;
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值