登 录
/*
给定一颗k叉树的前序和后序遍历序列
求这个k叉树一共可能有多少种
求每个节点孩子节点的个数n,然后从m个位置中选n个位置给这n个孩子,一共有c(m ,n )中选法,
把所有节点的这个值相乘即可
*/
#include <iostream> #define MAX_N 26 using namespace std; int countv[MAX_N + 1]; char pre[MAX_N + 1]; char post[MAX_N + 1]; int m; //计算组合数 int getC(int n, int m) { 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, countv[i]); return res; } //递归计算每个节点的儿子数 void countSons(int curPrePos, int curPostPos, int endPrePos) { if(curPrePos == endPrePos) return; int pPre = curPrePos + 1, postP; char c; while(pPre <= endPrePos) { c = pre[pPre]; countv[curPrePos]++; postP = curPostPos; while(post[postP] != c) postP++; countSons(pPre, curPostPos, pPre + (postP - curPostPos)); pPre = pPre + (postP - curPostPos) + 1; curPostPos = postP + 1; } } int main() { while(scanf("%d", &m) && m != 0) { scanf("%s%s", pre, post); memset(countv, 0, sizeof(countv)); countSons(0, 0, strlen(pre) - 1); printf("%d/n", getRes()); } return 0; }
抱歉!评论已关闭.