BZOJ1012:[JSOI2008]最大数

浅谈栈:https://www.cnblogs.com/AKMer/p/10278222.html

题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=1012

因为询问的是最大值,我们可以考虑把”在更后面有比这个数大的数“的数删掉。

那么就是单调栈维护了,然后对于后面\(limit\)个数字里最大值可以在栈上二分这个位置。

时间复杂度:\(O(n)\)

空间复杂度:\(O(n)\)

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;
typedef pair<int,int> pii;
#define ff first
#define ss second

const int maxn=2e5+5;

char opt[5];
pii stk[maxn];
int top,n,lstans,pps,cnt;

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

int main() {
	n=read(),pps=read();
	for(int i=1;i<=n;i++) {
		scanf("%s",opt+1);
		if(opt[1]=='Q') {
			int limit=read();
			int l=1,r=top;
			while(l<r) {
				int mid=(l+r)>>1;
				if(stk[top].ss-stk[mid].ss+1<=limit)r=mid;
				else l=mid+1;
			}
			lstans=stk[r].ff;
			printf("%d\n",lstans);
		}
		else {
			int x=(read()+lstans)%pps;
			while(top&&stk[top].ff<=x)top--;
			stk[++top]=make_pair(x,++cnt);
		}
	}
	return 0;
}
posted @ 2019-01-17 19:42  AKMer  阅读(111)  评论(0编辑  收藏  举报