poj 1240 前序和后序

给定m叉树的前序和后序序列,那么该m叉树可能有多少种情况呢?

很好的题目

思路:

依据前序和后序序列,可以计算出每一个结点的子节点个数,然后利用乘法原理,计算树的个数

如何确定子节点个数呢?

对于前序:   AXXXXX

对于后序:   XXXXXA

而言,其余的皆为A的子结点

对于前序:   ABXXXX

对于后序:   XXXBXA

而言,B是A的子树,而后序B前面的结点均为B的子结点,检测到这一步,A的子树个数可以加1

扫描完数组一遍,A的子树个数就确定了,那么A的可能性为组合数 C ( M, N) ,N为计算出的子树个数,M为分叉数

类似的,对于子树B,采用相同的方法计算子树的个数,于是采用

自顶向下递归求解

#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <set>
#include <cctype>
#include <algorithm>
#include <cmath>
#include <deque>
#include <queue>
#include <map>
#include <queue>
#include <list>
#include <iomanip>
using namespace std;                                               
///
///
#define INF 0xffffff7
#define maxn 30
#define max(a,b)(a>b?a:b)
///
char pre[maxn];
char post[maxn];
int cntNum[maxn];
int m;
int getC(int n, int m)  //计算组合数C(M,N)
{
	if (m == 0 || n == m)
		return 1;
	else
		return getC(n - 1, m - 1) + getC(n - 1, m);
}
int getRes()  //计算最终的结果
{
	int res = 1;
	for (int i = 0; i < strlen(post); i++)
		res *= getC(m, cntNum[i]);
	return res;
}
void GetNum(int curPrePos, int curPostPos, int endPrePos)
{
	if (curPrePos == endPrePos) //已经到结尾,不再计算
		return;
	int pPre = curPrePos + 1, postP; //取前序pre的下一个结点
	while(pPre <= endPrePos)
	{
		char c = pre[pPre];     
		cntNum[curPrePos]++;//当前结点子树个数加1
		postP = curPostPos;
		while(post[postP] != c) //找到当前结点第一个子树的所有子节点
			postP++;    
		GetNum(pPre, curPostPos, pPre + (postP - curPostPos)); //递归计算子树子节点个数
		pPre = pPre + (postP - curPostPos) + 1; //指针后移,继续计算
		curPostPos = postP + 1;                 //指针后移,继续就算
	}
}
int main()
{
	///
	int i, j;
	while (1)
	{
		scanf("%d", &m);
		if (m == 0)
			break;
		scanf("%s%s", pre, post);
		memset(cntNum, 0, sizeof(cntNum));
		GetNum(0, 0, strlen(pre) - 1);
		printf("%d\n", getRes());
	}
	
	///
    return 0;
}                                              



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值