DP+数学
看了很多博客才理解,附上一篇很详细的题解:https://blog.csdn.net/bossup/article/details/9915647。看完了可能还是不懂,根据题意和代码慢慢想吧。
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
自己的代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll dp[25][2];//dp[][0]放置排列尾部为高低情况,dp[][1]放置排列为低高情况
ll pl[25][25];//pl[i][j]:从i中选出j个有多少种情况
int main()
{
ll i,j;
for(i=1;i<=20;i++)
{
pl[i][0]=1;
pl[i][i]=1;
for(j=1;j<i;j++)
pl[i][j]=pl[i-1][j-1]+pl[i-1][j];//排列组合公式
}
dp[0][0]=1;
dp[0][1]=1;
dp[1][0]=1;
dp[1][1]=1;
for(i=2;i<=20;i++)//总数,每次加一即新放置的都是最高点
{
ll ans=0;//每个总数放置位置的总方法数
for(j=0;j<i;j++)//最高点位置
{
ans+=dp[j][0]*dp[i-j-1][1]*pl[i-1][j];//根据数组含义进行理解
}
dp[i][0]=ans/2;//排列尾部为高低情况与排列尾部为低高情况数量相等
dp[i][1]=ans/2;
}
ll p;
scanf("%lld",&p);
while(p--)
{
ll d,n;
scanf("%lld %lld",&d,&n);
if(n==1)
{
printf("%lld 1\n",d);
continue;
}
printf("%lld %lld\n",d,dp[n][0]*2);
}
return 0;
}