输入
5
1 2 3 4 5
2 1 4 -1
会爆
区间修改后区间最大值会出错
#include<bits/stdc++.h>
using namespace std;
struct node{
int l, r;
int maxx, sum;
int add;
}tree[400001];
int n, val[100001], op;
void build_tree(int p, int l, int r){ //构建线段树
if (l > r) return;
tree[p].l = l,tree[p].r = r;
if (l ==r){
tree[p].maxx = val[l];
tree[p].sum = val[l];
return;
}
int mid = (l + r) / 2;
build_tree(p * 2, l, mid);
build_tree(p * 2 + 1, mid + 1, r);
tree[p].maxx = max(tree[p * 2].maxx, tree[p * 2 + 1].maxx);
tree[p].sum = tree[p * 2].sum + tree[p * 2 + 1].sum;
}
void spread(int p){
if (tree[p].add){
tree[p * 2].add += tree[p].add;
tree[p * 2 + 1].add += tree[p].add;
tree[p * 2].sum += tree[p].add * (tree[p * 2].r - tree[2 * p].l + 1);
tree[p * 2 + 1].sum += tree[p].add * (tree[p * 2 + 1].r - tree[2 * p + 1].l + 1);
tree[p].add = 0;
}
}
int query(int op, int p, int l, int r){
if (tree[p].l >= l && tree[p].r <= r){
if (op == 1)return tree[p].maxx;
else if(op == 2) return tree[p].sum;
}
if (tree[p].r < l || tree[p].l > r) return 0;
if(op == 2) spread(p);
int s = 0;
if (tree[p * 2].r >= l){
if (op == 1)s = max(s, query(op, p * 2, l, r));
else if (op == 2) s += query(op, p * 2, l, r);
}
if (tree[p * 2 + 1].l <= r){
if (op == 1)s = max(s, query(op, p * 2 + 1, l, r));
else if (op == 2) s += query(op, p * 2 + 1, l, r);
}
return s;
}
void modify(int p, int l,int r, int k){ //将区间[l,r]+=k
if (l == r) tree[p].maxx = tree[p].sum;
if (tree[p].l >= l && tree[p].r <= r){
tree[p].sum += k * (tree[p].r - tree[p].l + 1);
tree[p].add += k;
return;
}
spread(p);
int mid = (l + r) / 2;
if (l <= mid) modify(p * 2, l, r, k);
if (r > mid) modify(p * 2 + 1, l, r, k);
tree[p].sum = tree[p * 2].sum + tree[p * 2 + 1].sum;
tree[p].maxx = max(tree[p * 2 + 1].maxx, tree[p * 2].maxx);
}
int main(){
cin >> n;
for (int i = 1;i <= n;i++) cin >> val[i];
build_tree(1, 1, n);
int l, r;
while (cin >> op){
if (op == 1){ //查询
int op1;
cin >> op1 >> l >> r;
// op1==1:查询[l,r]最大值
// op1==2:查询[l,r]的和
cout << query(op1, 1, l, r) << endl;
}
else if (op == 2){ //修改
int k;
cin >> l >> r >> k;
modify(1, l, r, k);
}
}
return 0;
}