----
源代码位于:https://github.com/yunwei37/myClassNotes
还有不少数据结构和算法相关的笔记以及pta题解哦x
----
PTA top level 练习里面的一道题目...挺简单的,就是读懂题目然后注意一下边界条件。
是浙江大学高级数据结构与算法课程的一个小作业啦
# 思路
就是两个最大上升子序列,从正反两个方向进行,然后把结果叠加到一起就好啦。不算注释的话30行代码...可以说非常少了x
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 (1Di+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.
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].
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.
20
1 3 0 8 5 -2 29 20 20 4 10 4 7 25 18 6 17 16 2 -1
10 14 25
5
-1 3 8 10 20
No peak shape
代码:
/*
Name: The Best Peak Shape
Author: zheng yusheng
Date: 21/04/19 14:27
Description: the solve of project "The Best Peak Shape" using dp algorithm
*/
#include
#include
#define max(a,b) (a>b?(a):(b))
/*forward dp, find the length of the increasing sequence end with the ith number*/
int up[10010];
/*backward dp, find the length of the decreasing sequence end with the ith number*/
int down[10010];
//the number sequence is stored here, begin at num[1];
int num[10010];
int main() {
int n,max,j;
scanf("%d",&n);//get the integer N
int i;
for(i=0; i=1; i--)
for(int j=n; j>=i+1; j--)
if (num[j] < num[i]) down[i] = max(down[i], down[j] + 1);
//add the results of the forward dp and backward together, and find the max one;
max=0;//the peak position of the max length peak shape(guard:the length is zero)
for(i=1; i<=n; ++i) {
if(up[i]==0||down[i]==0) continue;//skip results that cannot form a peak shape;
else if(up[i]+down[i]>up[max]+down[max])//if the lenth is larger, update the position of the num;
max=i;
else if(up[i]+down[i]==up[max]+down[max]&&abs(up[i]-down[i]) 0)//if there exist a solution, output the result
printf("%d %d %d",up[max]+down[max]+1,max,num[max]);
else printf("No peak shape\n");//no solution
return 0;
}