线段树,点修改
本题要点:
1、节点开个 max 表示区间 [l, r] 范围内的最大值。套用线段树 点修改 的模板。
执行相应的修改查询操作即可。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MaxN = 2e5 + 10;
int n, m;
int score[MaxN];
struct segTree
{
int l, r;
int max;
}tree[MaxN * 4];
void build(int p, int l, int r)
{
tree[p].l = l, tree[p].r = r;
if(l == r)
{
tree[p].max = score[l];
return;
}
int mid = (l + r) / 2;
build(p * 2, l, mid);
build(p * 2 + 1, mid + 1, r);
tree[p].max = max(tree[p * 2].max, tree[p * 2 + 1].max);
}
void change(int p, int l, int r, int x, int y) // score[x] = y
{
if(l == r)
{
tree[p].max = y;
return;
}
int mid = (l + r) / 2;
if(x <= mid)
{
change(p * 2, l, mid, x, y);
}else{
change(p * 2 + 1, mid + 1, r, x, y);
}
tree[p].max = max(tree[p * 2].max, tree[p * 2 + 1].max);
}
int ask(int p, int l, int r)
{
if(l <= tree[p].l && r >= tree[p].r)
{
return tree[p].max;
}
int val = -1;
int mid = (tree[p].l + tree[p].r) / 2;
if(l <= mid)
val = max(val, ask(p * 2, l, r));
if(r > mid)
val = max(val, ask(p * 2 + 1, l, r));
return val;
}
int main()
{
char cmd[3];
int x, y;
while(scanf("%d%d", &n, &m) != EOF)
{
for(int i = 1; i <= n; ++i)
scanf("%d", &score[i]);
build(1, 1, n);
for(int i = 0; i < m; ++i)
{
scanf("%s%d%d", cmd, &x, &y);
if(cmd[0] == 'U')
{
change(1, 1, n, x, y);
}else{
printf("%d\n", ask(1, x, y));
}
}
}
return 0;
}
/*
5 6
1 2 3 4 5
Q 1 5
U 3 6
Q 3 4
Q 4 5
U 2 9
Q 1 5
*/
/*
5
6
5
9
*/