单点时限: 2.0 sec
内存限制: 256 MB
A sequence of numbers is called a zig-zag sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a zig-zag sequence.
For example, 1,7,4,9,2,5 is a zig-zag sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, 1,4,7,2,5 and 1,7,4,5,5 are not zig-zag sequences, the first because its first two differences are positive and the second because its last difference is zero.
输入格式
Given a sequence of integers, sequence, return the length of the longest subsequence of sequence that is a zig-zag sequence. A subsequence is obtained by deleting some number of elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
sequence contains between 1 and 50 elements, inclusive.
Each element of sequence is between 1 and 1000, inclusive.
输出格式
output the length of the longest subsequence of sequence that is a zig-zag sequence.
样例
input
10
1 17 5 10 13 15 10 5 16 8
output
7
input
6
1 7 4 9 2 5
output
6
题意:求区间正负相间最大个数
/*
思路:dp
dp[n][2]表示以a[n]结尾相减为正为负的个数。
dp[n][0]:表示以a[n]结尾相减为负的个数
dp[n][1]:表示以a[n]结尾相减为正的个数
转移方程为:
dp[i][0]=max(dp[j][1]+1,dp[i][0]) a[i]>a[j]
dp[i][1]=max(dp[j][0]+1,dp[i][1]) a[i]<a[j]
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int n;
cin>>n;
int a[n];
int M=1;
for(int i = 0; i < n; i++)
cin>>a[i];
int dp[n][2];//dp[n][0]存以a[n]结尾相减为正数
for(int i = 0; i < n; i++) {
dp[i][0]=dp[i][1]=1;
for(int j = 0; j < i; j++) {
if(a[i]-a[j]>0)
dp[i][0]=max(dp[j][1]+1,dp[i][0]);
if(a[i]-a[j]<0)
dp[i][1]=max(dp[j][0]+1,dp[i][1]);
}
}
cout<<max(dp[n-1][0],dp[n-1][1])<<endl;
return 0;
}