poj1240 Pre-Post-erous!(递归/m叉树前后序序列种数)

题目

给定m(1<=m<=20),代表m叉树,

和两个长度为1-26的字母串,分别代表树的前序和后序序列,

求这两个序列能确定多少种不同的树

思路来源

https://www.cnblogs.com/BobHuang/p/8227875.html

题解

本质区别是,

对于一个根固定的区间,第一棵子树对应一段前序和后序区间,第二棵对应一段……,

假设有x棵子树,则对应了C(m,x)种选法,

找到固定根时,根的每棵子树的前序后序区间,不断递归下去

 

这个题有一个弱化版51nod1832,是二叉树的情形,只是统计答案要用大数,

二叉树的左子树的根一定是前序的l+1位置,右子树的根一定是后续的R-1的位置

当然,本题中,把m改成2,套个BigInt,也可以直接过

代码

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
int n,m;
char pre[28],pos[28];
ll C(int a,int b){
    ll ans=1;
    for(int i=a-b+1;i<=a;i++)ans*=i;
    for(int i=2;i<=b;i++)ans/=i;
    return ans;
}
ll dfs(int l,int r,int L,int R){
    //printf("l:%d r:%d L:%d R:%d\n",l,r,L,R);
    if(l>=r){
        return 1;
    }
    int tr=0,now=L;//几棵子树
    ll ans=1;
    for(int i=l+1;i<=r;){
        int nex,len;
        for(int k=now;k<=R;++k){
            if(pre[i]==pos[k]){
                nex=k;
                break;
            }
        }
        tr++;
        len=nex-now+1;
        ans*=dfs(i,i+len-1,now,nex);//下一棵子树的前序区间[i,i+len-1],后序区间[now,nex] 长度均为len
        now=nex+1;//找到下一棵子树后序的左端点now
        i+=len;//找到下一棵子树前序的左端点i
    }
    ans*=C(m,tr);//m棵位置里选tr棵
    return ans;
}
int main(){
    while(~scanf("%d",&m) && m){
        scanf("%s%s",pre+1,pos+1);
        n=strlen(pre+1);
        printf("%lld\n",dfs(1,n,1,n));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章