HDU - 4489 The King’s Ups and Downs

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: 



or perhaps: 



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个士兵按照高低高低高低或者低高低高低高的位置站,一共有多少种站法

解题思路:定义dp[i][1]表示有i个人且开始为低高的方法数,dp[i][0]表示有i个人且开始为高低的方法数,假设所有人按照从低到高的顺序开始选择站队位置,则当第i个人插入在第j个位置时,前面有j个人,后面有i-j-1个人,总的方法数为sum=dp[j][0]*dp[i-j-1][1]*c[i-1][j],c[i-1][j]表示从插入前的i-1个人中选择j个人,dp[i][0]和dp[i][1]分别等于总的方法数的一半

AC代码:

#include
using namespace std;
const int maxn=50;
typedef long long LL;

LL dp[maxn][maxn],ans[maxn],c[maxn][maxn];

int main()
{
	c[0][0]=1;c[1][0]=1;
	c[1][1]=1;
	for(int i=2;i<=20;i++)
	{
		c[i][0]=1;
		c[i][i]=1;
		for(int j=1;j

 

你可能感兴趣的:(动态规划)