HDU 4489 The King’s Ups and Downs(组合DP)

来源:互联网 发布:淘宝男模特收入 编辑:程序博客网 时间:2024/05/19 13:07

作者:Accagain

链接:点击打开链接

原题

The King’s Ups and Downs


Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)


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:



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,求n个高矮不同的人排成一排使得高、矮波浪形依次排列的种数。

涉及知识及算法

对于n个人,设其高度分别为1,2,3,,,,,n.
对于第n个人,假设前面的n-1个人已经放好了,则有n个位置是可以放人的,第n个人的身高大于前n-1个人的任何人的身高。
对于任一位置j,左边的j-1个人的排列中,必须满足最后一个人一定是通过身高下降得到的,右边的n-j个人中,最开始的那个人一定通过升高得到后面一个人的。
因为任意两人的高度是不等的,所以人选一定能组成波浪形,所以前面j-1个人的组合情况是C(n-1,j-1)。
设状态dp[i][0]表示有i个人,并且最开始的那个人通过升高得到后面一个人的。
dp[i][1]表示有i个人,并且最后一个人是通过下降得到的。
很显然在人数相同的情况下,由对称性得 dp[i][0]=dp[i][1]=sum[i]/2 sum[i]为i个人总的满足要求的排列数。
对于第n个人放到位置j ,有C(n-1,j-1)*dp[j-1][0]*dp[n-j][1]种情况。

代码

#include <iostream>#include <cstdio>using namespace std;typedef long long ll;ll dp[30][2];ll sum[30];//求组合数ll C(int a,int b){    if(b==0) return 1;    ll res=1;    for(int i=0;i<b;i++)        res*=(a-i);    for(int i=1;i<=b;i++)        res/=i;    return res;}int main(){    //freopen("in.txt","r",stdin);    dp[0][0]=dp[0][1]=1;    dp[1][0]=dp[1][1]=1;    sum[1]=1;    for(int i=2;i<=20;i++)    {        for(int j=1;j<=i;j++)            sum[i]+=(dp[j-1][0]*dp[i-j][1]*C(i-1,j-1));        //由对称性        dp[i][0]=dp[i][1]=sum[i]/2;    }    int t,d,k;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&d,&k);        printf("%d %lld\n",d,sum[k]);    }    return 0;}


原创粉丝点击