51nod - 1153 选择子序列

长度为N的整数数组A,所有的数均不相同,假设下标从0开始。找到一个最长的数组B,B数组的长度为K,数值范围是0 - N - 1,记录的是A数组的下标。满足A[B[0]] > A[B[1]] > A[B[2]] >...A[B[K]],并且对任意连续的两项B[i]及B[i + 1],满足min(B[i],B[i + 1]) < j < max(B[i],B[i + 1]) 均有A[j] < A[B[i + 1]] ,求最大的K。例如:9, 10, 2, -1, 3, -5, 0, -3, 1, 12, 5, 8, -2, 6, 4。可以选出:12, 10, 3, 1, 0, -3。对应的下标为:9, 1, 4, 8, 6, 7(就是B数组),输出6。

Input

第1行:一个数N,表示A数组的长度。(1 <= N <= 50000)
第2 - N + 1行:每行1个数对应A数组的元素Ai(0 < Ai < 10^9)

Output

输出B数组最长的长度K。

Input示例

15
9
10
2
-1
3
-5
0
-3
1
12
5
8
-2
6
4

Output示例

6

思路:

利用单调递减栈,栈中相邻两个值的位置之间的数字必然小于两个相邻值的最小值。

#include <cstring>
#include <iostream>
#include <stack>
using namespace std;

const int SIZE = 50005;
int input[SIZE];
struct node
{
	node(int v, int n)
	{
		val = v;
		num = n;
	}
	int val;
	int num;
};

int main()
{
	int n;
	cin >> n;
	stack<node> buf;
	int a;
	int result = 0;
	for (int i = 0; i < n; i++)
	{
		cin >> a;
		int num = 0;
		while ((!buf.empty()) && a > buf.top().val)
		{
			num = max(num, buf.top().num);
			buf.pop();
		}
		num++;
		int size = buf.size() + 1;
		num = max(num, size);
		buf.push(node(a, num));
		result = max(result, num);
	}

	cout << result << endl;
	
	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值