uva 10312——Expression Bracketing

该问题要求计算在所有n个字母的括号表达式中,非二叉树结构的组合数量。例如,4个字母有11种可能的括号表达式,其中前6种是非二叉树结构。输入为单个整数n,输出对应非二叉树括号表达式的总数。题目提供了样例输入和输出,例如n=3时有1种,n=4时有6种。解决方案与卡特兰数和超卡特兰数有关,通过超卡特兰数减去卡特兰数得出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In this problem you will have to find in how many ways n letters can be bracketed so that the bracketing is non-binary bracketing. For example 4 letters have 11 possible bracketing: 

xxxx, (xx)xx, x(xx)x, xx(xx), (xxx)x, x(xxx), ((xx)x)x, (x(xx))x, (xx)(xx), x((xx)x), x(x(xx)). Of these the first six bracketing are not binary. Given the number of letters you will have to find the total number of non-binary bracketing.

Input

The input file contains several lines of input. Each line contains a single integer n (0. Input is terminated by end of file. 

Output

For each line of input produce one line of output which denotes the number of non binary bracketing with n letters.

Sample Input

3
4
5
10

Sample Output

1
6
31
98187

 

题意:给你n个相乘的x,可以用括号来改变优先级,问在所有的情况中,有多少个是非二叉树的情况(开始没理解,后来查了binary的所有意思,二进制,二叉树,二分,看到二叉树,想到不久前水图论的时候看到的二叉树表达式,通了)。

 

思路:挣扎了两三天,并不知道从哪里下手,后来观察题目要求的反面,突然觉得有点眼熟,画了二叉树,恍然大悟就是卡特兰数啊,具体的卡特兰数的分析:卡特兰数的性质及其应用

里面已经讲了卡特兰和超卡特兰,本题就是用超卡特兰减去卡塔兰。

 

Code

 

//方法一:
#include <iostream>
#include <cstdlib>

using namespace std;

long long C[30] = {0};
long long S[30] = {0};

int main()
{
S[0] = S[1] = S[2] = 1;
for (int i = 3 ; i < 30 ; ++ i)
S[i] = (3*(2*i-3)*S[i-1]-(i-3)*S[i-2])/i;
C[0] = C[1] = 1;
for (int i = 2 ; i < 30 ; ++ i)
for (int j = 0 ; j < i ; ++ j)
C[i] += C[j]*C[i-j-1];

int n;
while (cin >> n)
cout << S[n]-C[n-1] << endl;

return 0;
}


//方法二直接交表
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
using namespace std;

typedef long long ll;
const int N=27;
ll super_catalan[N]={0,1,1,3,11,45,197,903,4279,20793,103049,518859,2646723,13648869,71039373,372693519,1968801519,10463578353,55909013009,300159426963,1618362158587,8759309660445,47574827600981,259215937709463,1416461675464871,7760733824437545,42624971294485657};
ll catalan[N]={0,1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452};
int main()
{
int n;
while (~scanf("%d",&n)&&n)
printf("%lld\n",super_catalan[n]-catalan[n]);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值