hdu-4489-The King’s Ups and Downs(DP)

                                                                         Problem Description

The king has guards of all different heights. Rather than line them up in increasing or decreasing height order, he wants to line them up so each guard is either shorter than the guards next to him or taller than the guards next to him (so the heights go up and down along the line). For example, seven guards of heights 160, 162, 164, 166, 168, 170 and 172 cm. could be arranged as:

hdu-4489-The King’s Ups and Downs(DP)_第1张图片


or perhaps:

hdu-4489-The King’s Ups and Downs(DP)_第2张图片


The king wants to know how many guards he needs so he can have a different up and down order at each changing of the guard for rest of his reign. To be able to do this, he needs to know for a given number of guards, n, how many different up and down orders there are:

For example, if there are four guards: 1, 2, 3,4 can be arrange as:

1324, 2143, 3142, 2314, 3412, 4231, 4132, 2413, 3241, 1423

For this problem, you will write a program that takes as input a positive integer n, the number of guards and returns the number of up and down orders for n guards of differing heights.

Input

The first line of input contains a single integer P, (1 <= P <= 1000), which is the number of data sets that follow. Each data set consists of single line of input containing two integers. The first integer, D is the data set number. The second integer, n (1 <= n <= 20), is the number of guards of differing heights.

Output

For each data set there is one line of output. It contains the data set number (D) followed by a single space, followed by the number of up and down orders for the n guards.

Sample Input

4

1  1

2  3

3  4

4  20

Sample Output

1  1

2  4

3  10

4 740742376475050

 

解题思路:

       对于 n 个人的身高,可以简单的可能是1,2,3 .... n。第 n 个人在插入队伍的时候,比任意一个数字都要大,因此可以放在 n 个位置。n 在任意位置 j 处,j-1 到 j 一定是增加的顺序,而 j 到 j+1 一定是减小的顺序。前面 j-1 个人可以又C(i-1,j-1)种情况。

       令dp[i][0] 表示最后一个数字是下降得来的,dp[i][1] 表示最后一个数字是上升得来的,同时我们可以很明显的看出,dp[i][1]与dp[i][0] 的数量是相等的,可以直接用sum[i]/2 得到。

#include 
using namespace std;

#define LL long long

int C(int a,int b){
    if(b == 0)
        return 1;

    LL ans  = 1;
    for(int i = 0; i < b; i++){
        ans *= (a-i);
    }

    for(int i = 1; i <= b; i++){
        ans /= i;
    }

    return ans;
}

int main(){
    int p,n,d;
    cin >> p;

    LL dp[25][2];
    LL sum[25];
    LL flag = 0;

    dp[0][0] = dp[0][1] = 1;
    dp[1][0] = dp[1][1] = 1;
    sum[1] = 1;

    for(int i = 2;i < 25; ++i){
        sum[i] = 0;
        for(int j = 1;j <= i; ++j){
            flag = dp[j-1][0] * dp[i-j][1] * C(i-1,j-1);
            sum[i] += flag;
        }
        dp[i][0] = dp[i][1] = sum[i]/2;
    }

    while(p--){
        cin >> d >> n;
        cout << d << " " << sum[n] << endl;
    }
    return 0;
}

 

你可能感兴趣的:(算法学习)