Description
现在请求你维护一个数列,要求提供以下两种操作:1、 查询操作。语法:Q L 功能:查询当前数列中末尾L
个数中的最大的数,并输出这个数的值。限制:L不超过当前数列的长度。2、 插入操作。语法:A n 功能:将n加
上t,其中t是最近一次查询操作的答案(如果还未执行过查询操作,则t=0),并将所得结果对一个固定的常数D取
模,将所得答案插入到数列的末尾。限制:n是非负整数并且在长整范围内。注意:初始时数列是空的,没有一个
数。
Input
第一行两个整数,M和D,其中M表示操作的个数(M <= 200,000),D如上文中所述,满足D在longint内。接下来
M行,查询操作或者插入操作。
Output
对于每一个询问操作,输出一行。该行只有一个数,即序列中最后L个数的最大数。
Sample Input
5 100
A 96
Q 1
A 97
Q 1
Q 2
A 96
Q 1
A 97
Q 1
Q 2
Sample Output
96
93
96
93
96
这道题可以用线段树或者单调队列,下面是程序:
线段树:
- #include<stdio.h>
- #include<iostream>
- using namespace std;
- const int N=800005;
- struct tree{
- int lc,rc,key;
- }t[N];
- int k;
- void build(int rt,int l,int r){
- if(l==r){
- t[rt].key=t[rt].lc=t[rt].rc=0;
- return;
- }
- int m=(l+r)>>1;
- t[rt].lc=++k;
- t[rt].rc=++k;
- build(t[rt].lc,l,m);
- build(t[rt].rc,m+1,r);
- t[rt].key=max(t[t[rt].lc].key,t[t[rt].rc].key);
- }
- void add(int rt,int l,int r,int k,int w){
- if(l==r&&l==k){
- t[rt].key=w;
- return;
- }
- int m=(l+r)>>1;
- if(k<=m){
- add(t[rt].lc,l,m,k,w);
- }
- else{
- add(t[rt].rc,m+1,r,k,w);
- }
- t[rt].key=max(t[t[rt].lc].key,t[t[rt].rc].key);
- }
- int ask(int rt,int l,int r,int a,int b){
- if(l==a&&r==b){
- return t[rt].key;
- }
- int m=(l+r)>>1;
- if(b<=m){
- return ask(t[rt].lc,l,m,a,b);
- }
- if(a>m){
- return ask(t[rt].rc,m+1,r,a,b);
- }
- return max(ask(t[rt].lc,l,m,a,m),ask(t[rt].rc,m+1,r,m+1,b));
- }
- void read(int &s){
- s=0;
- int f=1;
- char c=getchar();
- while((c<'0'||c>'9')&&c!='-'){
- c=getchar();
- }
- if(c=='-'){
- f=-1;
- c=getchar();
- }
- while(c>='0'&&c<='9'){
- s*=10;
- s+=c-'0';
- c=getchar();
- }
- s*=f;
- }
- void ch(char &c){
- c=getchar();
- while(c!='A'&&c!='Q'){
- c=getchar();
- }
- }
- int main(){
- int n,mod,q=0,x,l=0,i;
- char c;
- read(n);
- read(mod);
- build(0,1,n);
- for(i=0;i<n;i++){
- ch(c);
- read(x);
- if(c=='A'){
- add(0,1,n,++l,(q+x)%mod);
- }
- else{
- printf("%d\n",q=ask(0,1,n,l-x+1,l));
- }
- }
- return 0;
- }