【题解】bzoj P1012 最大数(线段树)

可以用线段树解决这个问题,对某个叶子节点修改其值,最后寻找在某个区间内的最大值。这里只需要把儿子结点相加的操作变为父亲结点=儿子节点的最大值即可。

#include<cstdio>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
const int maxn=200010;
int m,mod;
int tot=0;
int mmax[maxn*8];
void add(int now,int l,int r,int x,int y)
{
	if(l==r)
	{
		mmax[now]=y;
		return ;
	}
	int mid=(l+r)/2;
	if(x<=mid) add(now*2,l,mid,x,y);
	else add(now*2+1,mid+1,r,x,y);
	mmax[now]=max(mmax[now*2],mmax[now*2+1]);
}
int getsum(int now,int l,int r,int x,int y)
{
	int mid=(l+r)/2;
	if(x<=l&&y>=r)
	{
		return mmax[now];
	}
	int ans=-1e9;
	if(x<=mid) ans=max(ans,getsum(now*2,l,mid,x,y));
	if(mid+1<=y) ans=max(ans,getsum(now*2+1,mid+1,r,x,y));
	return ans;
}
int main()
{
	for(int i=1;i<=maxn*8;i++)
	{
		mmax[i]=-1e9;
	}
	scanf("%d%d",&m,&mod);
	int t=0;
	int tmp;
	for(int i=1;i<=m;i++)
	{
		char c=getchar();
		while(c==' '||c=='\n') c=getchar();
		scanf("%d",&tmp);
		if(c=='A')
		{
			tot++;
			add(1,1,m,tot,(t+tmp)%mod);
		}
		if(c=='Q')
		{
			t=getsum(1,1,m,tot-tmp+1,tot);
			printf("%d\n",t);
			
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Rem_Inory/article/details/81276479