线段树模板

单点更新区间查询,维护最小值

#include 
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 110;
int a[maxn];//原数组 
int minv[4 * maxn];//维护最小值

/*
单点更新
区间查询 
*/ 

//维护 
void pushup(int id) {
    minv[id] = min(minv[id << 1], minv[id << 1 | 1]);
}

//建树 
void build(int id, int l, int r) {
    if (l == r) {
        minv[id] = a[l];
        return;
    }
    int mid = (l + r) >> 1;
    build(id << 1, l, mid);
    build(id << 1 | 1, mid + 1, r);
    pushup(id);
}

//更新 
void update(int id, int l, int r, int x, int v) {
    if (l == r) {
        minv[id] = v;
        return;
    }
    int mid = (l + r) >> 1;
    if (x <= mid) {
        update(id << 1, l, mid, x, v);
    } else {
        update(id << 1 | 1, mid + 1, r, x, v);
    }
    pushup(id);
}

//查询 
int query(int id,int l,int r,int x,int y){
    if(x <= l && r <= y){
        return minv[id];
    }
    int mid = (l + r) >> 1;
    int ans = inf;
    if( x <= mid){
        ans = min(ans,query(id << 1, l, mid, x,y));
    }
    if( y > mid){
        ans = min(ans,query( id<< 1 | 1,mid + 1,r,x,y));
    }
    return ans;
}

int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
    }
    build(1, 1, n);
    int q;
    cin >> q;
    for (int i = 0; i < q; ++i) {
        int x, v;
        cin >> x >> v;
        update(1, 1, n, x, v);
    }
    int p;
    cin >> p;
    for (int i = 0; i < p; ++i) {
        int l, r;
        cin >> l >> r;
        cout << query(1, 1, n, l, r) << endl;
    }
    return 0;
}

区间更新,区间查询,维护赋值修改

void up(int p)
{
    if (!p) return;
    s[p] = s[p * 2] + s[p * 2 + 1];
}

void down(int p, int l, int r)
{
    if (col[p])
    {
        int mid = (l + r) / 2;
        s[p * 2] = col[p] * (mid - l + 1);
        s[p * 2 + 1] = col[p] * (r - mid);
        col[p * 2] = col[p * 2 + 1] = col[p];
        col[p] = 0;
    }
}

void modify(int p, int l, int r, int x, int y, int c)
{
    if (x <= l && r <= y)
    {
        s[p] = (r - l + 1) * c;  //仅修改该结点
        col[p] = c;  //增加标记,子结点待修改
        return;
    }
    down(p, l, r);  //下传lazy标记
      int mid = (l + r) / 2;
    if (x <= mid) modify(p * 2, l, mid, x, y, c);
    if (y > mid) modify(p * 2 + 1, mid + 1, r, x, y, c);
    up(p);
}

你可能感兴趣的:(线段树模板)