Pills
Problem Description
Aunt Lizzie takes half a pill of a certain medicine every day. She starts with a bottle that contains N pills.
On the first day, she removes a random pill, breaks it in two halves, takes one half and puts the other half back into the bottle.
On subsequent days, she removes a random piece (which can be either a whole pill or half a pill) from the bottle. If it is half a pill, she takes it. If it is a whole pill, she takes one half and puts the other half back into the bottle.
In how many ways can she empty the bottle? We represent the sequence of pills removed from the bottle in the course of 2N days as a string, where the i-th character is W if a whole pill was chosen on the i-th day, and H if a half pill was chosen (0 <= i < 2N). How many different valid strings are there that empty the bottle?
Input
The input will contain data for at most 1000 problem instances. For each problem instance there will be one line of input: a positive integer N <= 30, the number of pills initially in the bottle. End of input will be indicated by 0.
Output
For each problem instance, the output will be a single number, displayed at the beginning of a new line. It will be the number of different ways the bottle can be emptied.
Sample Input
6
1
4
2
3
30
0
Sample Output
132
1
14
2
5
3814986502092304
Source
The 2011 Rocky Mountain Regional Contest
這個題的答案就是卡特蘭數。
分析如下:
小藥丸與藥丸之間沒有任何區別,不如一開始就把所有的藥丸看做是左半和右半。這就成了典型的圓括號正確匹配的問題了。強制先拿為左半,就不難想象出是卡特蘭數的規律了。(本質上左右兩半都是一樣的,為了方便類比,所以看做是左半和右半)
#include<iostream>
#include<cstring>
using namespace std;
#define maxn 120
long long int a[maxn][500];//儲存卡特蘭數
long long int b[maxn];//n對應卡特蘭數的長度
void Catalan()//卡特蘭數計算函數
{
//計算公式:h(n)=h(n-1)*(4*n-2)/(n+1);
//大數運算
long long int i, j, len, carry, temp;
a[1][0] = b[1] = 1;
a[0][0] = 0;
len = 1;
for (i = 2; i <= 100; i++)
{
for (j = 0; j < len; j++)//len 始終等於前一個卡特蘭數的位數
{
a[i][j] = a[i - 1][j] * (4 * (i - 1) + 2);
}
carry = 0;
for (j = 0; j < len; j++)//進位操作
{
temp = a[i][j] + carry;
a[i][j] = temp % 10;
carry = temp / 10;
}
while (carry)
{
a[i][len++] = carry % 10;
carry /= 10;
}
carry = 0;
for (j = len - 1; j >= 0; j--)//除法
{
temp = carry * 10 + a[i][j];
a[i][j] = temp / (i + 1);
carry = temp % (i + 1);
}
while (!a[i][len - 1])
len--;
b[i] = len;
}
}
int main()
{
int n;
Catalan();//打表
while (~scanf("%d", &n)&&n)
{
for (int k = b[n] - 1; k >= 0; k--)
{
printf("%d", a[n][k]);
}
printf("\n");
}
return 0;
}