题目链接:
题意:
给你n个身高高低不同的士兵(身高为1~n)。问你把他们按照波浪状排列(高低高或低高低)有多少方法数。
题目输入输出:
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。 我们可以从身高从小到大的去放。我们考虑,前面已经有i-1个人现在要放第i个人的情况。由于i是最后放的所以他一定是最高的。无论他在哪个位置一定都是波峰。
所以在他前面的部分结尾一定为高低。在他后面的部分开始一定为低高。这样才能形成高低高低高。如果知道前面结尾高低的方法数n和后面开始低高的方法数m。那么在该位置的方法数就为n*m。而前面的个数和后面的个数是不确定的所以要枚举放置的位置j,前面的个数就为j-1,而后面的个数就为i-j。
由于状态转移要用到结尾高低的方法数和后面开始低高的方法数。所以我们用dp[i][0]表示有i个人且i个人结尾为高低的方法数。dp[i][1]表示有i个人且开始为低高的方法数。那么有i个人排列的方法数就为ans[i]+=dp[j-1][0]*dp[i-j][1]*c[i-1][j-1]。c[i-1][j]为方法数。因为不确定前面j个人的标号。所以要在i-1个人中选j个人出来。(在这里一定要理解,因为n个人身高是1~n,所以选出来的j个人的身高肯定是能从高到底排序的,就是说这里只需要看相对身高,更直白的说就是选出来的j个人的排列数和身高为1~j的排列数是相等的,之前就一直卡在这儿不能理解)。
那怎么更新状态转移需要用到的dp[i][1]和dp[i][0]呢?把i个士兵排好后无非两种情况。开始为低高。开始为高低。那么排列的逆序也满足条件。也就是说结尾为高低的方法数和开始为低高的方法数相同。而对于人数一定的情况。开始为低高的人数和开始为高低的人数相等。所以dp[i][0]=dp[i][1]=ans[i]/2。
代码:
#include <stdio.h>
#include <algorithm>
#define LL long long
using namespace std;
LL Calc(int a,int b) //计算组合数
{
LL i;
if(b==0)return 1;
LL ret1=1;
LL ret2=1;
LL ret3=1;
for(i=a;i>=1;i--)
{
ret1*=i;
}
for(i=b;i>=1;i--)
{
ret2*=i;
}
for(i=a-b;i>=1;i--)
{
ret3*=i;
}
return ret1/(ret2*ret3);
}
int main()
{
LL dp[21][2];
int n;
LL ans[21];
int i,j;
dp[0][1]=dp[0][0]=1;
dp[1][1]=dp[1][0]=1; //初始化
ans[1]=1;
for(i=2;i<=20;i++)
{
ans[i]=0;
for(j=1;j<=i;j++)
{
ans[i]+=dp[j-1][0]*dp[i-j][1]*Calc(i-1,j-1);
}
dp[i][0]=dp[i][1]=ans[i]/2; //由对称可知
}
int num;
int cnt;
scanf("%d",&n);
while(n--)
{
scanf("%d %d",&cnt,&num);
printf("%d %lld\n",cnt,ans[num]);
}
return 0;
}