单点更新:
#include <cstdio>
#include <algorithm>
using namespace std;
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
const int maxn = 222222;
int MAX[maxn<<2];
void PushUP(int rt) {
MAX[rt] = max(MAX[rt<<1] , MAX[rt<<1|1]);
}
void build(int l,int r,int rt) {
if (l == r) {
scanf("%d",&MAX[rt]);
return ;
}
int m = (l + r) >> 1;
build(lson);
build(rson);
PushUP(rt);
}
void update(int p,int sc,int l,int r,int rt) {
if (l == r) {
MAX[rt] = sc;
return ;
}
int m = (l + r) >> 1;
if (p <= m) update(p , sc , lson);
else update(p , sc , rson);
PushUP(rt);
}
int query(int L,int R,int l,int r,int rt) {
if (L <= l && r <= R) {
return MAX[rt];
}
int m = (l + r) >> 1;
int ret = 0;
if (L <= m) ret = max(ret , query(L , R , lson));
if (R > m) ret = max(ret , query(L , R , rson));
return ret;
}
int main() {
int n , m;
while (~scanf("%d%d",&n,&m)) {
build(1 , n , 1);
while (m --) {
char op[2];
int a , b;
scanf("%s%d%d",op,&a,&b);
if (op[0] == 'Q') printf("%d\n",query(a , b , 1 , n , 1));
else update(a , b , 1 , n , 1);
}
}
return 0;
}
区域更新
#include <stdio.h>
#include <algorithm>
using namespace std;
typedef __int64 ll;
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
const int maxn = 300000;
char str[10];
struct node{
int l, r;
int add;//延迟更新标记
int sum;
}tree[(maxn<<2)+10];
int a[maxn];
void pushup(int rt) {
if(tree[rt].l==tree[rt].r) return ;
tree[rt].sum = (tree[rt<<1].sum+tree[rt<<1|1].sum);
return;
}
void pushdown(int rt){
if(tree[rt].l==tree[rt].r) return;
if(tree[rt].add==-1) return;
tree[rt<<1].add = tree[rt<<1|1].add = tree[rt].add;
tree[rt<<1].sum = (tree[rt<<1].r - tree[rt<<1].l + 1) * tree[rt].add;
tree[rt<<1|1].sum = (tree[rt<<1|1].r - tree[rt<<1|1].l + 1) * tree[rt].add;
tree[rt].add = -1;
}
void build(int l,int r,int rt) {
tree[rt].l = l;
tree[rt].r = r;
tree[rt].sum = 1;
tree[rt].add = -1;
if (l == r) {
tree[rt].sum = 1;
return;
}
int m = (l + r) >> 1;
build(lson);
build(rson);
pushup(rt);
return;
}
void update(int l,int r,int z,int rt){
if(l==tree[rt].l && r==tree[rt].r){
tree[rt].sum = (tree[rt].r - tree[rt].l + 1) * z;
tree[rt].add = z;
return;
}
pushdown(rt);
int m = tree[rt].l + tree[rt].r>>1;
if(r <= m) update(l,r,z,rt<<1);
else if(l >m)update(l,r,z,rt<<1|1);
else{
update(l,m,z,rt<<1);
update(m+1,r,z,rt<<1|1);
}
pushup(rt);
return ;
}
ll query(int l,int r,int rt){
if(tree[rt].l == l&&r == tree[rt].r ){
return tree[rt].sum;
}
pushdown(rt);
int m = tree[rt].l+tree[rt].r>>1;
if(r <= m) return query(l,r,rt<<1);
else if(l > m) return query(l,r,rt<<1|1);
else return (query(l,m,rt<<1)+query(m+1,r,rt<<1|1));
}
int main(){
int n, m,t;
scanf("%d", &t);
int cas = 1;
while(t--){
scanf("%d%d", &n, &m);
build(1,n,1);
while(m--){
int L, R, Z;
scanf("%d%d%d", &L, &R, &Z);
update(L,R,Z,1);
}
printf("Case %d: ",cas++);
printf("The total value of the hook is %d.\n",query(1,n,1));
}
return 0;
}