PAT顶级题解目录
In many research areas, one important target of analyzing data is to find the best "peak shape" out of a huge amount of raw data full of noises. A "peak shape" of length L is an ordered sequence of L numbers { D1, ⋯, DL } satisfying that there exists an index i (1<i<L) such that D1<⋯<Di−1<Di>Di+1>⋯>DL.
Now given N input numbers ordered by their indices, you may remove some of them to keep the rest of the numbers in a peak shape. The best peak shape is the longest sub-sequence that forms a peak shape. If there is a tie, then the most symmetric (meaning that the difference of the lengths of the increasing and the decreasing sub-sequences is minimized) one will be chosen.
Input Specification:
Each input file contains one test case. For each case, the first line gives an integer N (3≤N≤104). Then N integers are given in the next line, separated by spaces. All the integers are in [−10000,10000].
Output Specification:
For each case, print in a line the length of the best peak shape, the index (starts from 1) and the value of the peak number. If the solution does not exist, simply print "No peak shape" in a line. The judge's input guarantees the uniqueness of the output.
Sample Input1:
20
1 3 0 8 5 -2 29 20 20 4 10 4 7 25 18 6 17 16 2 -1
Sample Output1:
10 14 25
Sample Input2:
5
-1 3 8 10 20
Sample Output2:
No peak shape
题目大意:给出一个序列,找到其最长的一个子序列(可以跳过部分数字)满足先升序后降序。如果有两个同长度这样的子序列,那么取升序部分和降序部分数目差较小的那一个。
解题思路:设置两个数组,left和right,分别用来存放该数字左边的最长的升序序列和后边的降序序列。以left[i]为例,要求left[i]只要遍历0到i-1处的数,当某个位置j(0到i-1之间)的数字比num[i]小,那么left[i] 可以为 left[j]+1,只要找到max(left[j]+1)即可。
代码:
#include <bits/stdc++.h>
using namespace std;
int n, sum = 0, Index, minn;
int main(){
scanf("%d", &n);
std::vector<int> num(n), left(n,0), right(n,0);
for(int i = 0; i < n; ++ i)
scanf("%d", &num[i]);
for(int i = 1; i < n; ++ i)
for(int j = 0; j < i; ++ j)
if(num[i] > num[j])
left[i] = max(left[i], left[j]+1);
for(int i = n-2; i >= 0; -- i)
for(int j = n-1; j > i; -- j)
if(num[j] < num[i])
right[i] = max(right[i], right[j]+1);
for(int i = 0; i < n; ++ i){
if(left[i] == 0 || right[i] == 0)
continue;
if((left[i]+right[i]) > sum || ((left[i]+right[i]) == sum && abs(left[i]-right[i]) < minn)){
sum = left[i]+right[i];
Index = i;
minn = abs(left[i] - right[i]);
}
}
if(sum == 0)
printf("No peak shape\n");
else
printf("%d %d %d\n", sum+1, Index+1, num[Index]);
}