51nod-1153 选择子序列

思路:这题的解题思路十分巧妙,看了大佬的思路,由代码来谈谈个人的理解

Code:

/*
题目要求的是a[l-r]间比两端小的元素,因此可以用一个单调栈(小的先出栈)来求解,
*/
#include<iostream>
#include<stack>
using namespace std;

struct node{
	int x;
	int len;
};
int n,ans;
stack<node> sta;

int main()
{
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=0,x;i<n;++i)
	{
		cin>>x;
		int Max=0;
		node t;
		//对于数组a[],比较当前值x与栈顶元素的大小,将所有小于x的数出栈,同时记录其最大长度,
		while(!sta.empty()){
			t=sta.top();
			if(x>t.x){
				Max=max(Max,t.len);
				sta.pop();
			}else	break;
		}
		//x有两种构造B数组的方法,一是和刚刚栈中小于它的元素构成,二是现在栈中元素构成,取其最大值 
		Max=max(Max,(int)sta.size())+1;
		sta.push(node{x,Max});	//将其入栈,此时对于x来说Max是构成B数组的最大长度 
		ans=max(ans,Max);
	}
	cout<<ans<<endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/C_13579/article/details/81332879
今日推荐