虽然这道洛谷题不算难,我拿来练练线段树,但是一直过不了,后来才发现代码中有一处不懂的错误,根本原因还是对线段树理解不到位。记录下来
#include<iostream>
using namespace std;
#define int long long
const int inf=-4611686018427387904;//-(1<<62)
int n,mod,t,cnt=1;
struct node{
int l,r,val;
}tree[800010];
void build(int l,int r,int rt){
tree[rt].l=l;
tree[rt].r=r;
if(l==r){
tree[rt].val=inf;
}
else{
int m=l+r>>1;
build(l,m,2*rt);
build(m+1,r,2*rt+1);
tree[rt].val=max(tree[2*rt].val,tree[2*rt+1].val);
}
}
void updata(int l,int r,int rt,int x){
if(l<=tree[rt].l&&tree[rt].r<=r){
tree[rt].val=x;
return ;
}
if(l>tree[rt].r||r<tree[rt].l){
return;
}
updata(l,r,2*rt,x);
updata(l,r,2*rt+1,x);
tree[rt].val=max(tree[rt*2].val,tree[rt*2+1].val)%mod;
}
int ask(int l,int r,int rt){
if(l<=tree[rt].l&&tree[rt].r<=r){
return tree[rt].val;
}
if(l>tree[rt].r||r<tree[rt].l){
return inf;
}
//int m=tree[rt].r+tree[rt].l>>1;
//return max(ask(l,m,rt*2),ask(m+1,r,rt*2+1))%mod;
return max(ask(l,r,rt*2),ask(l,r,rt*2+1))%mod;
}
signed main(){
ios::sync_with_stdio(0);
cin>>n>>mod;
build(1,200005,1);
while(n--){
char c;
int x;
cin>>c>>x;
if(c=='A'){
updata(cnt,cnt,1,(x+t)%mod);
cnt++;
}
else{
if(x)t=ask(cnt-x,cnt-1,1)%mod;
else t=0;
cout<<t<<endl;
}
}
return 0;
}
//int m=tree[rt].r+tree[rt].l>>1;
//return max(ask(l,m,rt*2),ask(m+1,r,rt*2+1))%mod;
return max(ask(l,r,rt*2),ask(l,r,rt*2+1))%mod;
之前一直用上面注释的代码,后来发现没有道理的,自己以前只是记住了错误的代码,总之还是改正了。