Description
Now I ask you to maintain an array and provide the following two operations: 1. Query operation. Syntax: QL Function: Query
the largest number among the last L numbers in the current sequence, and output the value of this number. Restriction: L does not exceed the length of the current sequence. 2. Insert operation. Syntax: A n Function:
Add t, where t is the answer of the most recent query operation (if the query operation has not been performed, then t=0), and the result is
modulo a fixed constant D, the The resulting answer is inserted at the end of the sequence. Restrictions: n is a non-negative integer and is in the range of long integers. Note: Initially, the number column is empty, without a
number.
Input
The first line contains two integers, M and D, where M represents the number of operations (M <= 200,000), and D, as described above, satisfies D within longint. Next
M lines, query operation or insert operation.
Output
For each query operation, output one line. The row has only one number, the maximum number of the last L numbers in the sequence.
Sample Input
A 96
Q 1
A 97
Q 1
Q 2
Sample Output
93
96
This problem can use line segment tree or monotonic queue, the following is the program:
Segment tree:
- #include<stdio.h>
- #include<iostream>
- usingnamespace std;
- constint 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;
- }