CF319B Psychos in a Line 单调栈

原题:http://codeforces.com/problemset/problem/319/B

题解:给一个序列,若该位置的值大于左边就可以将右边吃掉,问要进行多少次这样的操作。可以用单调栈,栈中存两个值,大小和答案。若当前元素大于栈顶元素就弹出,若没有弹出任何元素,就只进行了一次操作,若将栈弹空,则为0,当前的答案为弹出的最大值+1。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1e5+10;
int n,stack[N][2],top,ans;
int main(){
//	freopen("test.in","r",stdin);
	scanf("%d",&n);top=0;ans=0;
	for(int i=1,x;i<=n;i++){
		scanf("%d",&x);int maxm=0;
		while(top && x>stack[top][0])maxm=max(maxm,stack[top][1]), top--;
		stack[++top][0]=x;
		if(top==1) {
			stack[top][1]=0;
		}else stack[top][1]=maxm+1;
		ans=max(ans,stack[top][1]);
	}
	printf("%d\n",ans);
	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_39689721/article/details/87951648