AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 200005;
struct node{
int l,r,maxn;
}tree[N<<2];
int a[N];
void build(int m,int l,int r){
tree[m].l = l;
tree[m].r = r;
if(l == r){
tree[m].maxn = a[l];
return ;
}
int mid = (l+r)>>1;
build(m<<1,l,mid);
build((m<<1)|1,mid+1,r);
tree[m].maxn = max(tree[m<<1].maxn,tree[(m<<1)|1].maxn);
}
void update(int m,int x,int val){
if(tree[m].l == x && tree[m].r == x){
tree[m].maxn = val;
return ;
}
int mid = (tree[m].l+tree[m].r)>>1;
if(x <= mid)
update(m<<1,x,val);
else
update((m<<1)|1,x,val);
tree[m].maxn = max(tree[m<<1].maxn,tree[(m<<1)|1].maxn);
}
int query(int m,int l,int r){
if(tree[m].l == l && tree[m].r == r)
return tree[m].maxn;
int mid = (tree[m].l+tree[m].r)>>1;
if(r <= mid)
return query(m<<1,l,r);
if(l > mid)
return query((m<<1)|1,l,r);
return max(query(m<<1,l,mid),query((m<<1)|1,mid+1,r));
}
int main(){
int n,m;
while(~scanf("%d%d",&n,&m)){
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
build(1,1,n);
char op[10];
int x,y;
while(m--){
scanf("%s%d%d",op,&x,&y);
if(op[0] == 'Q'){
printf("%d\n",query(1,x,y));
}
else if(op[0] == 'U'){
update(1,x,y);
}
}
}
return 0;
}
本文介绍了一种使用C++语言实现的线段树数据结构,用于快速进行区间最大值查询与元素更新操作。通过构建线段树并利用递归方法实现节点更新和查询,该算法在复杂度上显著优于传统的遍历方法。
553

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



