HDU 4165 Pills (DP卡特兰数列)

来源:互联网 发布:淘宝店铺头像在线制作 编辑:程序博客网 时间:2024/04/28 02:32

Pills

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1297    Accepted Submission(s): 902


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
61423300
 

Sample Output
132114253814986502092304
 

Source

大体题意:
一开始瓶子里有n 个完整药片,每次只能吃半个药片,若遇到完整药片,则会吃掉半个,在把剩下半个药片放回瓶子里,问吃药片的方法数!
思路:
仔细想想可以把问题转换一下,最后肯定2n长度的序列,肯定是n个完整药片和n个半个药片。
并且当前半个药片的数量不超过 前面完整药片的数量!
所以:
可以转换成卡特兰数列!
状态转移:
dp[i][j] = dp[i-1][j] + dp[i][j-1];
排列数量中来源,i-1完整,j个不完整,和  i个完整,j-1个不完整!
最后dp[n][n]就是答案!

注意要打表啊,不然会超时!
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 100 + 10;typedef long long ll;ll dp[maxn][maxn];void init(){    for (int i = 0; i <= 30; ++i)dp[i][0] = 1;    for (int i = 1; i <= 30; ++i)        for (int j = 1; j <= i; ++j)            dp[i][j] = dp[i-1][j] + dp[i][j-1];}int main(){    int n;    init();    while(scanf("%d",&n) == 1 && n){        printf("%I64d\n",dp[n][n]);    }    return 0;}



0 0