以下面的题目为例(题目和代码在最后面),给定一个数列(长度最大为10000),求出最长的先增后减子序列长度及个数。做法是先求出以每一个位置结尾的最长单增子序列长度以及以该位置开头的最长单减子序列长度,然后遍历所有位置找出最大先增后减子序列长度。
以最长单增序列(LIS)为例,由于不仅需要整个序列LIS的长度,还要保存以每个位置为结尾位置的LIS长度。记以a[i]结尾的LIS长度为dp[i],则
dp[i] = max{dp[j] | a[j] < a[i]} + 1
这就是一个RMQ问题,涉及单点更新和单点查询,所有选择用线段树求解。
后面统计子序列个数时,记以a[i]结尾的最长子序列个数为num[i],则
num[i] = sum{num[j] | j < i && dp[j] + 1 == dp[i]}
最朴素的做法是遍历1到i - 1,但这样会超时,由于dp[i] <= 10000,故提前保存每个dp[i]的位置,用coll[i]保存所有dp[j] = i的j,那么对于num[i],只需遍历集合coll[dp[j] - 1],统计子序列个数的时间复杂度可以降为O(n)。
下面是原题和代码:
Mountain Engineering |
A sequence in which the value of elements first increase and then decrease is called Mountain- Sequence. In a valid Mountain-Sequence there should be at least one element in the increasing and at least one element in the decreasing arm.
For example, "1 3 5 9 17 12" is a valid Mountain-Sequence having five elements in the increasing arm namely 1, 3, 5, 9 and 17, and 1 element in the decreasing arm namely 12 . But none of the sequence "1 4 6" or "9 8 6" are Mountain-Sequence since "1 4 6" has
no element in the decreasing part while "9 8 6" has no element in the increasing part.
A sub-sequence of a sequence is obtained by deleting zero or more elements from the sequence. For example definition "7", "2 10", "8 2 7 6", "8 2 7 10 6" etc are valid sub-sequences of "8 2 7 10 6"
Given a sequence of N numbers finding its longest sub-sequence which is a Mountain-Sequence is the main problem here. The bigger problem is to find, how many such sequences exist.
To make it clearer, assume that the longest mountain-sequence in a given sequence is of length l. Then you have to find all subsequences which are mountain sequences of length l. Hence, you have to find NUMBER of these maximum length Mountain Sequences that
can be extracted from the given sequence.
Input
- The first line contains the no of test cases(T).
- First line of each test case contains an integer N , the number of element in the given sequnce.
- Then follows N integers A1, A2.... An, Ai is ith element of the given sequence. These numbers will be newline separated.
Output
Print the NUMBER of longest-length Mountain Sequences in the given sequence.
Note:- A sequence with only one element is not a mountain-Sequence and no two adjacent elements in a Mountain-Sequence are of same value. Assume that two different elements of a sequence, which have the same value, represent different entities. E.g., if a sequence
contains the element 7 at two places, then you have to consider two different sub-sequences having element 7 ONLY.
.
Constraints
- 1 ≤ T ≤ 100
- 1 ≤ Ai ≤ 10000
Example
Input: 1 12 5 4 7 89 10 23 29 56 8 5 30 70 Output: 2
Explanation
Example case 1.
The longest Mountain Sequences have length 8. The mountain sequences in this sequence are:
4 7 10 23 29 56 8 5 5 7 10 23 29 56 8 5