hdu 4165 (找规律)

本文探讨了一项趣味算法挑战:计算一位女士如何能在多种方式下将装有一定数量药片的瓶子清空。该问题涉及到动态规划和递归算法,并提供了一个具体的实现示例。
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
解析:用s[i][j]表示结果,i, j,分别表示整片的和半片的。则s[i][j] = s[i-1][j+1] + s[i][j-1];因为吃整片的话半片就加一而整片就减一,吃半片了半片就减一。用记忆化搜索时注意初始化。s[0][j] = 1,
 
#include <cstdio>
#include <cstring>

__int64 s[31][31];
__int64 cal(int n, int i)
{
    if (s[n][i] > 0)
    {
        return s[n][i];
    }
    if (n<0 || i<0)
    {
        return 0;
    }
    s[n][i] = cal(n-1, i+1) + cal(n, i-1);
    return s[n][i];
}

int main(void)
{
    int n;

    while (scanf("%d", &n), n)
    {
        memset(s, 0, sizeof(s));
        s[1][0] = 1;
        s[1][1] = 2;
        //s[0][n] = 1;
        for (int i=0; i<31; i++)
        {
            s[0][i] = 1;
        }
        printf("%I64d\n", cal(n, 0));
    }

    return 0;
}

 

3814986502092304

 

转载于:https://www.cnblogs.com/bucuo/archive/2013/04/01/2994019.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值