1017 The Best Peak Shape (35 分)(C++)

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 { D​1​​, ⋯, D​L​​ } satisfying that there exists an index i (1<i<L) such that D​1​​<⋯<D​i−1​​<D​i​​>D​i+1​​>⋯>D​L​​.

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≤10​4​​). 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]);
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值