「FJOI2012」 RP - 单调队列

题目大意

有三种操作:

  • new a
  • leave
  • query

意义分别为:

  • 在队列中加入一个为a的数
  • 去除队首元素,保证有元素
  • 查询队列中最大值,保证有元素

输出每次查询的值。

分析

明显的单调队列。维护一个单调队列,记录元素位置。如果执行了leave操作,就让flag=当前队尾,一开始flag=0,每次入队时直接普通的单调队列入队,输出是判断队首直到队首>=flag,输出队首。

代码

#include <iostream>
#include <cstdio>
#include <deque>
using namespace std;
int a[1000005],n,x,tail,head,flag;
char op[10];
deque<int> q;
int main() {
	scanf("%d",&n);
	head=1;
	while (n--) {
		scanf("%s",op);
		if (op[0]=='n') {
			scanf("%d",&a[++tail]);
			while (!q.empty()&&a[q.back()]<=a[tail]) q.pop_back();
			q.push_back(tail);
		} else if (op[0]=='l') {
			head++;
			flag=head;
		} else {
			while (!q.empty()&&q.front()<flag) q.pop_front();
			printf("%d\n",a[q.front()]);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sin_Yang/article/details/82081763