HDU 4489The King’s Ups and Downs(dp递推)

The King’s Ups and Downs

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


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个人,身高依次是1~n让你求高低高。。。或者低高低。。这样的方案数。

            解题思路:高中的时候,好像做过一些此类的题目。需要递推,讲一下大概思路。实际上真的不麻烦。已知前面1~n-1的方案数,然后算第n个。从n-1里面选i个排好序的放在n的前面,选择的方法组合数为C(n-1,i)个,(选好数目后排序方案数为dp[i]/2,因为低高低与高低高的数目是一样的,不过1需要特判只有一种),后面的方案数为dp[n-1-i]/2个,同理。。。然后把三个数相乘即可。具体实现见代码。  当然数据量只有20,你也可以打表,不过不要忘了使用int64LL

            题目地址:The King’s Ups and Downs

AC代码:
#include
#include
#include
#include
using namespace std;
__int64 dp[22];

__int64 pow(int x)
{
     __int64 sum=1;
     for(int i=1;i<=x;i++)
          sum*=i;
     return sum;
}

__int64 c(int n,int m)  //算组合数
{
     return pow(n)/pow(m)/pow(n-m);
}
int main()
{
     memset(dp,0,sizeof(dp));
     dp[1]=1,dp[2]=2,dp[3]=4;
     int i,j;
     for(i=4;i<=20;i++)
     {
         dp[i]+=dp[i-1];  //最高的在两边*c(i,0)
         for(j=1;j>1)*c(i-1,j);
             else
               dp[i]+=(dp[j]>>1)*(dp[i-1-j]>>1)*c(i-1,j);
         }
     }
     int tes,cas,x;
     scanf("%d",&tes);
     while(tes--)
     {
          scanf("%d%d",&cas,&x);
          printf("%d %I64d\n",cas,dp[x]);
     }
     return 0;
}



            

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