题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4489点击打开链接
The King’s Ups and Downs
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 684 Accepted Submission(s): 492
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
Sample Output
1 1 2 4 3 10 4 740742376475050
解释起来有点复杂
首先 这是一个像波一样的 我们将高的称做波峰 矮的称做波谷
当新增加的一人插在队伍两边的时候 a[i]+=a[i-1]
当新增的人插在中间的时候 我们就对其中的一段进行排列组合
同时注意 选取的这两段的两端必须同为波峰或者波谷 而这种情况出现为当前这段总数的1/2
因此就可以知道 当前的a[i] 除了放在两边意外 还有内部所有排列组合可能出现的情况的递推 而这些就是计算新增加元素在内部的个数
注意排列组合其中一段为1时特判
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include