题目1044:Pre-Post

来源:互联网 发布:windows阻止软件自启 编辑:程序博客网 时间:2024/05/22 14:18
题目描述:

        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. 

样例输入:
2 abc cba2 abc bca10 abc bca13 abejkcfghid jkebfghicda
样例输出:
4145

207352860

C++代码:

#include<iostream>#include<string>using namespace std;int n;string s1,s2;long cont(int m,int n){    long a=1,b=1;    for(int i=0;i<m;i++){        a*=(m-i);        b*=(n-i);    }    return b/a;}long dfs(string s1,string s2,int n){    if(s1.length()==1)        return 1;    else{        long sum=1;        int Count =0;        s1=s1.substr(1);        s2=s2.substr(0,s2.length()-1);        while(s1.length()!=0){            int p = s2.find(s1[0]);            string tmp1=s1.substr(0,p+1);            string tmp2=s2.substr(0,p+1);            s1=s1.substr(p+1);            s2=s2.substr(p+1);            Count++;            sum*=dfs(tmp1,tmp2,n);        }        return cont(Count,n)*sum;    }}int main(){    while(cin>>n>>s1>>s2){        cout<<dfs(s1,s2,n)<<endl;    }    return 0;}


原创粉丝点击