洛谷 P1198 [JSOI2008]最大数
最大数
此题是一道适合线段树初学者拿来练手的好题,不需要过多的复杂操作(如pushdown, lazy tag等)。
此题需要做的只是在末尾加点和区间查询最大值操作即可。
Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
//Mystery_Sky
//
#define M 1000005
#define maxn 1000010
#define ll long long
#define Mid (l+r)>>1
struct Tree{
int x;
Tree *lc, *rc;
}dizhi[M<<1], *root = &dizhi[0];
int m, d, t=0, T;
void build(Tree *tree, int l, int r)
{
if(l == r) {
tree->x = 0;
return;
}
int mid = Mid;
tree->lc = &dizhi[++t];
tree->rc = &dizhi[++t];
build(tree->lc, l, mid);
build(tree->rc, mid+1, r);
tree->x = max(tree->lc->x, tree->rc->x);
}
void update(Tree *tree, int l, int r, int x, int d)
{
if(l == r) {
tree->x = d;
return;
}
int mid = Mid;
if(x <= mid) update(tree->lc, l, mid, x, d);
else update(tree->rc, mid+1, r, x, d);
tree->x = max(tree->lc->x, tree->rc->x);
}
int query(Tree *tree, int l, int r, int x, int y)
{
if(x <= l && y >= r) return tree->x;
int mid = Mid;
int ans = 0;
if(x <= mid) ans = max(ans, query(tree->lc, l, mid, x, y));
if(y > mid) ans = max(ans, query(tree->rc, mid+1, r, x, y));
return ans;
}
int main() {
scanf("%d%d", &m, &d);
int n = 1000000;
build(root, 1, n);
char a;
int b;
int num = 0;
for(int i = 1; i <= m; i++) {
cin >> a >> b;
if(a == 'A') {
num++;
update(root, 1, n, num, (b + T)%d);
}
if(a == 'Q') {
T = query(root, 1, n, num-b+1, num);
printf("%d\n", T);
}
}
return 0;
}
唯愿,青春不辜负梦想,未来星辰闪耀