问题 F: The King’s Ups and Downs
时间限制: 1 Sec 内存限制: 128 MB
题目描述
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 arranged 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.
输入
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.
输出
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.
样例输入
复制样例数据
4 1 1 2 3 3 4 4 20
样例输出
1 1 2 4 3 10 4 740742376475050
题解:
按照题意符合条件的序列应该就是波动系列
dp1[i][j] 表示 i 个数 第一个数小于等于 j 并且第一个数比第二个大 的种数
dp2[i][j] 表示 i 个数 第一个数小于等于 j 并且第一个数比第二个小 的种数
所以:
dp1[i][j] = dp1[i][j - 1] + dp2[i - 1][j - 1];
dp2[i][j] = dp2[i][j - 1] + (dp1[i - 1][i - 1] - dp1[i - 1][j - 1]);
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e7 + 10;
ll dp1[22][22];
ll dp2[22][22];
int main() {
dp1[1][1] = 1;
dp2[1][1] = 1;
for(int i = 2; i <= 20; i++) {
for(int j = 1; j <= i; j++) {
dp1[i][j] = dp1[i][j - 1] + dp2[i - 1][j - 1];
dp2[i][j] = dp2[i][j - 1] + (dp1[i - 1][i - 1] - dp1[i - 1][j - 1]);
// cout << i << " " << j <<" " << dp1[i][j]<<endl;
}
}
int T;
scanf("%d", &T);
int n, m;
ll ans;
while(T--) {
scanf("%d %d", &n, &m);
if(m == 1) ans = 1;
else ans = dp1[m][m] + dp2[m][m];
printf("%d %lld\n", n, ans);
}
return 0;
}