hdu 4489 The 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): 172    Accepted Submission(s): 106


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
 

Source
Greater New York 2012
 
思路:
假设现在要算ans[i],则前i-1个已经算好,将前i-1个数分成两边(左边j个,右边i-1-j个),然后插入i就够了。为保证插入后满足条件,则需满足左边以波谷结尾,右边以波谷开头。用dp[i][0]、dp[i][1]维护这两个数之后就可以往下推了,推的时候当然也要计算当前的dp的值。
ps:dp[i][0]和dp[i][1]的值是相等的,因为两者镜面对称,一一对应。

感想:
dp呀dp,最重要的还是推方程,要思维发散,敢想,敢尝试。

代码:
#include 
#include 
#include 
#define maxn 25
using namespace std;

int n,m;
long long cnt;
long long ans[maxn],dp[maxn][2],C[maxn][maxn];

void calC()      // 杨辉三角求组合数
{
    int i,j;
    memset(C,0,sizeof(C));
    for(i=0;i<=20;i++)
    {
        C[i][0]=1;
    }
    for(i=1;i<=20;i++)
    {
        for(j=1;j<=20;j++)
        {
            C[i][j]=C[i-1][j]+C[i-1][j-1];
        }
    }
}
void solve()    // 算答案
{
    int i,j,k;
    ans[1]=1;
    dp[0][0]=dp[0][1]=dp[1][0]=dp[1][1]=1;
    for(k=2;k<=20;k++)
    {
        cnt=0;
        for(i=0;i>1;   // 计算dp的值 因为下面推要用到
    }
}
int main()
{
    int i,j,t,test;
    calC();
    solve();
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&test,&n);
        printf("%d %I64d\n",test,ans[n]);
    }
    return 0;
}


 

你可能感兴趣的:(dp)