The King's Ups and Downs
64-bit integer IO format: %lld Java class name: Main
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:
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.
Source
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 const int maxn = 23; 5 LL dp[maxn][2],c[maxn][maxn]; 6 void init(){ 7 for(int i = 0; i <= 20; ++i){ 8 c[i][0] = c[i][i] = 1; 9 for(int j = 1; j < i; ++j) 10 c[i][j] = c[i-1][j-1] + c[i-1][j]; 11 } 12 dp[1][0] = dp[1][1] = dp[0][0] = dp[0][1] = 1; 13 for(int i = 2; i <= 20; ++i){ 14 LL tmp = 0; 15 for(int j = 0; j < i; ++j) 16 tmp += dp[j][0]*dp[i - j - 1][1]*c[i-1][j]; 17 dp[i][0] = dp[i][1] = (tmp>>1); 18 } 19 } 20 int main(){ 21 init(); 22 int kase,cs,n; 23 scanf("%d",&kase); 24 while(kase--){ 25 scanf("%d%d",&cs,&n); 26 printf("%d %lld ",cs,n == 1?1:dp[n][0]<<1); 27 } 28 return 0; 29 }