[luogu1198][JSOI2008]最大数

传送门

最初用线段树写,莫名其妙挂掉了……

于是开始单调栈:

  • 如果后来的数大于前面的数,那么前面的数一定不会作为答案,出栈。
  • 否则直接插入即可,并记录编号。

那么查询操作,只需要二分查找即可。

#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 200005

struct stack {
	int val,num;
}st[MAXN];
int top = 0;
int M,D;
long long last = 0;

inline void add(int x,int num) {
	while(top>0&&st[top].val<x) top--;
	st[++top] = (stack){x,num};
}

inline int get_ans(int R) {
	int l = 1,r = top;
	while(l<r) {
		int mid = (l+r)>>1;
		if(st[mid].num<R) l = mid + 1;
		else r = mid;
	}
	return st[l].val;
}

inline int get_opt() {
	char ch = getchar();
	while(ch!='A'&&ch!='Q') ch = getchar();
	return ch=='A' ? 1 : 2;
}

int main() {

	int opt;
	long long num;
	scanf("%d%d",&M,&D);
	int cnt = 0;

	for(int i=1;i<=M;++i) {
		
		opt = get_opt();
		scanf("%lld",&num);
		
		if(opt==1) add((int)((num+last)%D),++cnt);
		else {
			last = get_ans(cnt-((int)num)+1);
			printf("%d\n",(int)last);
		}
	}

	return 0;
}
posted @ 2018-12-07 23:12  Neworld1111  阅读(134)  评论(0编辑  收藏  举报