P1198 [JSOI2008]最大数 线段树入门

#include 
#define ll long long
const int maxn = 200005;
using namespace std;
ll mod;
struct N{
	ll val,mx;
}no[maxn<<2];
void build(int p,int l,int r){
	no[p].val = -1e18;
	no[p].mx = -1e18;
	if(l==r)return ;
	int mid = (l+r)>>1;
	build(p<<1,l,mid);
	build(p<<1|1,mid+1,r);
}
void update(int p,int l,int r,int id,ll val){
	if(l>r)return ;
	if(l==r){
		no[p].val = val;
		no[p].mx = val;
		return ;
	}
	int mid = (l+r)>>1;
	if(id<=mid)update(p<<1,l,mid,id,val);
	else if(id>mid)update(p<<1|1,mid+1,r,id,val);
	no[p].mx = max(no[p<<1].mx,no[p<<1|1].mx)%mod;
}
ll query(int p,int l,int r,int L,int R){
	if(l>r)return -1e18;
	if(L<=l&&R>=r){
		return no[p].mx;
	}
	int mid = (l+r)>>1;
	long long as = -1e18;
	if(L<=mid)as = max(as,query(p<<1,l,mid,L,R));
	if(R>mid)as = max(as,query(p<<1|1,mid+1,r,L,R));
	return as;
}
int main()
{
	int n = 0,m;
	char op[2];
	ll t=0,q;
	scanf("%d %lld",&m,&mod);
	build(1,1,maxn);
	for(int i=1;i<=m;i++){
		scanf("%s",op);
		if(op[0]=='Q'){
			int l;	scanf("%d",&l);
			t = query(1,1,maxn,n-l+1,n);
			printf("%lld\n",t);
		}else {
			scanf("%lld",&q);
			n++;
			update(1,1,maxn,n,(q+t)%mod);
		}
	}
	return 0;
}

 

你可能感兴趣的:(浅谈线段树)