题面
序列两种操作:
Q L:输出末尾L个数中的最大值
A n:将上一次查询的数t加上n再模d,插入到序列尾
操作数 n <= 200 000
分析
Q 操作用查询区间最大值即可完成,A 操作需要能够 add 元素。
线段树明显可以,理解也比较简单
这里采用树状数组维护区间最大值的 板子 来满足这两种操作。
代码
类封装的最值
#include "cstdlib"
#include <iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<string.h>
#include<string>
using namespace std;
#define lowbit(x) (x&(-x))
class Binary_Indexed_Trees_max//区间最大值
{
private:
const static int MAXN = 200010;
int A[MAXN];//原数组
int C[MAXN];
int N=MAXN;
public:
void updata(int x,int v)
{
A[x] = v;
int lx, i;
while (x <= N)
{
C[x] = A[x];
lx = lowbit(x);
for (i = 1; i < lx; i <<= 1)
C[x] = max(C[x], C[x - i]);
x += lowbit(x);
}
}
int query(int x, int y)
{
int ans = -2000000000;
while (y >= x)
{
ans = max(A[y], ans);
y--;
for (; y - lowbit(y) >= x; y -= lowbit(y))
ans = max(C[y], ans);
}
//C[y]是[ y-lowbit(y)+1 , y ]内的最大值
//y-lowbit(y) > x ,则query(x,y) = max( C[y] , query(x, y-lowbit(y)) );
//y-lowbit(y) <=x,则query(x,y) = max( A[y] , query(x, y-1);
return ans;
}
}BIT;
int main()
{
ios::sync_with_stdio(false);
int m, d;
cin >> m >> d;
int t = 0,cnt=0;
char opt;
int adj;
for (int i = 0; i < m; i++)
{
cin >> opt >> adj;
if (opt == 'A') {
BIT.updata(++cnt, (adj + t)%d);
}
else {
t = BIT.query(cnt - adj + 1, cnt);
cout << t << endl;
}
}
return 0;
}
本文介绍了一种使用树状数组和线段树解决序列操作问题的方法,具体包括查询区间最大值和在序列末尾插入经过特定运算的元素。通过实例演示了如何利用树状数组维护区间最大值,以及线段树在此类问题中的应用。
367

被折叠的 条评论
为什么被折叠?



