知道前序序列和后序序列求二叉树的个数+大数

来源:互联网 发布:cad椭圆指定数据怎么画 编辑:程序博客网 时间:2024/06/06 21:33

知道前序序列和后序序列求二叉树的个数+大数

题意:

​ 给出一个二叉树的前序遍历和后序遍历,问有多少个满足这样结构的二叉树?

思路:

​ 直接画一个最简单的二叉树,比如根节点恰好只有一个儿子,那么写出前序遍历和后序遍历会发现,根据两个遍历结构无法判断二叉树根节点的儿子是左儿子还是右儿子,那么其实只要找出这样的结构有多少个就行了,那么答案就是2的多少次方。

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long ll;const int N = 10005;struct BigInt{    const static int mod = 10000;    const static int DLEN = 4;    int a[600],len;    BigInt()    {        memset(a,0,sizeof(a));        len = 1;    }    BigInt(int v)    {        memset(a,0,sizeof(a));        len = 0;        do        {            a[len++] = v%mod;            v /= mod;        }while(v);    }    BigInt operator +(const BigInt &b)const    {        BigInt res;        res.len = max(len,b.len);        for(int i = 0;i <= res.len;i++)            res.a[i] = 0;        for(int i = 0;i < res.len;i++)        {            res.a[i] += ((i < len)?a[i]:0)+((i < b.len)?b.a[i]:0);            res.a[i+1] += res.a[i]/mod;            res.a[i] %= mod;        }        if(res.a[res.len] > 0) res.len++;        return res;    }    BigInt operator *(const BigInt &b)const    {        BigInt res;        for(int i = 0; i < len; i++)        {            int up = 0;            for(int j = 0;j < b.len;j++)            {                int temp = a[i] * b.a[j] + res.a[i+j] + up;                res.a[i+j] = temp%mod;                up = temp/mod;            }            if(up != 0)            res.a[i + b.len] = up;        }        res.len = len + b.len;        while(res.a[res.len - 1] == 0 &&res.len > 1)            res.len--;        return res;    }    void output()    {        printf("%d",a[len-1]);        for(int i = len-2;i >=0 ;i--)            printf("%04d",a[i]);        printf("\n");    }};BigInt ans(1);int PreStr[10005];int Length;int PostStr[10005];int count1;void calc(int a1,int b1,int a2,int b2){    int i;    if(a1 < 0 || a2 < 0 || b1 >= Length || b2 >= Length) return;    if(a1>=b1)  return;    if(a2>=b2) return;    for(i=a2; i<=b2-1; i++)    {        if(PreStr[a1+1] == PostStr[i])  break;    }    if(i == b2-1)  count1++;    calc(a1+1,a1+1+(i-a2),a2,i);    calc(a1+1+(i-a2)+1,b1,i+1,b2-1);}int main(){//    freopen("in.txt","r",stdin);    scanf("%d",&Length);    for(int i = 0;i < Length; i++)        scanf("%d",&PreStr[i]);    for(int i = 0;i < Length; i++)        scanf("%d",&PostStr[i]);    count1 = 0;    calc(0,Length-1,0,Length-1);    for(int i = 1;i <= count1; i++) {        ans = ans*BigInt(2);    }    ans.output();    return 0;}
阅读全文
0 0
原创粉丝点击