题面
题解
因为题中最多m次操作,所以最多有m个节点,那么我们就可以提前建立一颗M*4节点的线段树,那么对于A操作,就变成了在某一个位置修改数,那么Q操作就变成了查询区间的最大值,其他就是线段树模板了
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int N = 2e5;
int m, p;
struct Node {
int l, r;
int maxn; //最大值
} tr[N * 4];
void pushup(Node &u, Node &l, Node &r) {
u.maxn = max(l.maxn, r.maxn);
}
//向上由子节点更新父节点的信息
void pushup(int u) {
pushup(tr[u], tr[u << 1], tr[u << 1 | 1]);
}
//建树(此题建一颗空树)
void build(int u, int l, int r) {
if (l == r) tr[u] = {l, r, 0};
else {
tr[u] = {l, r};
int mid = (l + r) >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
}
//单点修改
void modify(int u, int x, int v) {
if (tr[u].l == x && tr[u].r == x) tr[u].maxn = v;
else {
int mid = (tr[u].l + tr[u].r) >> 1;
if (x <= mid) modify(u << 1, x, v);
else modify(u << 1 | 1, x, v);
pushup(u);
}
}
//区间查询
Node query(int u, int l, int r) {
if (l <= tr[u].l && tr[u].r <= r) return tr[u];
else {
int mid = (tr[u].l + tr[u].r) >> 1;
if (r <= mid) return query(u << 1, l, r);
else if (l > mid) return query(u << 1 | 1, l, r);
else {
Node res;
Node left = query(u << 1, l, r);
Node right = query(u << 1 | 1, l, r);
pushup(res, left, right);
return res;
}
}
}
int main() {
cin >> m >> p;
build(1, 1, m);
int n = 0, last = 0;
while (m--) {
string op;
int x;
cin >> op >> x;
if (op == "A") {
modify(1, n + 1, (x + last) % p);
n++;
} else {
last = query(1, n - x + 1, n).maxn;
cout << last << endl;
}
}
return 0;
}