题目
http://www.lydsy.com/JudgeOnline/problem.php?id=1012
题解
不1A的话就找块冻豆腐撞死吧。
线段树。
(后来补上的:)
看了黄学长的代码发现其实可以单调栈乱搞。因为序列的尾端一个元素进来的时候,前面不大于它的元素就永远不会被查到了,所以维护一个单调下降的单调栈(要记录序号),然后每次查询的时候二分查找到第一个序号大于等于L的就行了。
代码
//线段树
#include <cstdio>
#include <algorithm>
#define inf 0x7fffffff
#define maxm 200010
using namespace std;
struct node
{
int l, r, max;
node *lch, *rch;
}*root;
int tot, M, D;
void ins(node *p, int w)
{
int mid=p->l+p->r>>1;
p->max=max(w,p->max);
if(p->l==p->r)return;
if(tot<=mid)ins(p->lch,w);
else ins(p->rch,w);
}
int find(node *p, int l, int r)
{
int mid=p->l+p->r>>1, ans=-inf;
if(l<=p->l and r>=p->r)return p->max;
if(l<=mid)ans=max(ans,find(p->lch,l,r));
if(r>mid)ans=max(ans,find(p->rch,l,r));
return ans;
}
void build(node *p, int l, int r)
{
int mid=l+r>>1;
p->l=l,p->r=r,p->max=-inf;
if(l==r)return;
build(p->lch=new node,l,mid);
build(p->rch=new node,mid+1,r);
}
int main()
{
char ord[5];
int i, t=0, x;
scanf("%d%d",&M,&D);
build(root=new node,1,M);
for(i=1;i<=M;i++)
{
scanf("%s%d",ord,&x);
if(ord[0]=='Q')printf("%d\n",t=find(root,tot-x+1,tot));
else
{
tot++;
x=(x+t)%D;
ins(root,x);
}
}
return 0;
}
//单调栈
#include <cstdio>
#define maxm 200010
using namespace std;
int s[maxm], id[maxm], top;
int main()
{
char ord[5];
int t=0, M, D, l, r, mid, x, i, tot=0;
scanf("%d%d",&M,&D);
for(i=1;i<=M;i++)
{
scanf("%s%d",ord,&x);
if(*ord=='Q')
{
l=1,r=top,mid=l+r>>1;
x=(tot-x+1);
while(l<r)
{
if(id[mid]<x)l=mid+1;
else r=mid;
mid=l+r>>1;
}
printf("%d\n",t=s[l]);
}
else
{
tot++;
x=(x+t)%D;
while(top and s[top]<=x)top--;
s[++top]=x,id[top]=tot;
}
}
return 0;
}