整理一下线段树模板。
因为学的不精,复杂度是在我能力范围内最优的,以后学会了更优秀的再说吧。
分两块:
1:单点修改,区间查询
2:区间修改,区间查询
其实线段树的变种挺多的,这两个放在这方便修改。
我还是比较喜欢写成结构体的形式。。
1:单点修改,区间查询
#define lson i << 1
#define rson i << 1 | 1
template<class T> inline T qmax(T a, T b) { return a > b ? a : b; }
struct node{
int l, r, Max;
}tree[maxn<<2];
int a[maxn];
int n, m;
void push_up(int i){
tree[i].Max = qmax(tree[lson].Max, tree[rson].Max);
}
void build(int i, int l, int r){
tree[i].l = l, tree[i].r = r;
if(l == r) { tree[i].Max = a[l]; return ; }
int mid = (l + r) >> 1;
build(lson, l, mid);
build(rson, mid + 1, r);
push_up(i);
}
void update(int i, int pos, int val){
if(tree[i].l == pos && tree[i].r == pos) { tree[i].Max = val; return ; }
tree[i].Max = qmax(tree[i].Max, val);
int mid = (tree[i].l + tree[i].r) >> 1;
if(pos <= mid) update(lson, pos, val);
else update(rson, pos, val);
}
int Query(int i, int l, int r){
if(tree[i].l == l && tree[i].r == r) return tree[i].Max;
int mid = (tree[i].l + tree[i].r) >> 1;
if(r <= mid) return Query(lson, l, r);
else if(l > mid) return Query(rson, l, r);
else {
int ta = Query(lson, l, mid);
int tb = Query(rson, mid + 1, r);
return qmax(ta, tb);
}
}
int main()
{
while(~scanf("%d %d", &n, &m)){
rep(i, 1, n) scanf("%d", a + i);
build(1, 1, n);
rep(i, 1, m){
char c; int u, v; scanf(" %c %d %d", &c, &u, &v);
if(c == 'Q'){
printf("%d\n", Query(1, u, v));
} else {
update(1, u, v);
}
}
}
return 0;
}
2:区间修改,区间查询
#define lson x << 1
#define rson x << 1 | 1
int a[maxn];
struct Seg_Tree{//维护区间和
ll val[maxn<<2], lazy[maxn<<2];
inline void Up(int x){ val[x] = val[lson] + val[rson]; }
inline void Down(int x, int l, int mid, int r){
if(lazy[x]){
val[lson] += 1ll * lazy[x] * (mid - l + 1);
val[rson] += 1ll * lazy[x] * (r - mid);
lazy[lson] += lazy[x];
lazy[rson] += lazy[x];
lazy[x] = 0;
}
}
void build(int x, int l, int r){
lazy[x] = 0;
if (l == r){ val[x] = a[l]; return ; }
int mid = (l + r) >> 1;
build(lson, l, mid); build(rson, mid + 1, r);
Up(x);
}
void add(int x, int l, int r, int L, int R, int del){
if(l > R || r < L) return;
if (L <= l && r <= R){
val[x] += 1ll * del * (r - l + 1);
lazy[x] += del;
return;
}
int mid = (l + r) >> 1;
Down(x, l, mid, r);
add(lson, l, mid, L, R, del); add(rson, mid + 1, r, L, R, del);
Up(x);
}
ll query_Sum(int x, int l, int r, int L, int R){
if(l > R || r < L) return 0;
if(L <= l && r <= R) return val[x];
int mid = (l + r) >> 1;
Down(x, l, mid, r);
return query_Sum(lson, l, mid, L, R) + query_Sum(rson, mid + 1, r, L, R);
}
} tree;