segment tree template

#include<iostream>
#include<cstdio>
#include<string.h>
#include<math.h>
#include<string>
#include<map>
#include<set>
#include<vector>
#include<algorithm>
#include<queue>
#include<iomanip>
using namespace std;
const int INF = 0x3f3f3f3f;
const int NINF = 0xc0c0c0c0;
typedef long long ll;
const int maxn = 
// if len == 5, the size of segtree is 2^4-1;
// if len == 4, the size of segtree is 2^3-1;
void build(int l,int r,int pos){
    if(r- l == 1) {
        segtree[pos] = num[l];
        return ;
    }
    int mid = (r+l)/2;
    build(l,mid,pos*2+1);
    build(mid,r,pos*2+2);
    segtree[pos] = min(segtree[pos*2+1],segtree[pos*2+2]);
}

int query(int ql, int qr, int l, int r,int pos){
    if(qr <= l || ql >= r) return INF;
    if(ql <= l && qr >= r) return segtree[pos];
    int mid = (l+r) / 2;
    return min(query(ql,qr,l,mid,pos*2+1),query(qr,ql,mid,r,pos*2+2));
}

void updatepoint(int pos, int val){
    pos += n-1;                 //leaf
    segtree[pos] = val;
    while(pos > 0){             //update upward
        pos = (pos-1) / 2;
        segtree[pos] = min(segtree[pos*2+1],segtree[pos*2+2]);
    }
}

void updaterange(int ul,int ur,int l,int r,int pos,int delta){
    if(l >= r) return;
    if(lazy[pos] != 0){
        segtree[pos] += lazy[pos];
        if(r - l != 1){
            lazy[2*pos+1] += lazy[pos];
            lazy[2*pos+2] += lazy[pos];
        }
        lazy[pos] = 0;
    }
    if(ul >= r || ur <= l) return INF;
    if(ul <= l && ur >= r) {
        segtree[pos] += delta;
        if(r - l != 1){
            lazy[2*pos + 1] += delta;
            lazy[2*pos + 2] += delta;
        }
        return ;
    }

    int mid = (l+r) / 2;
    updaterange(ul,ur,l,mid,pos*2+1,delta);
    updaterange(ul,ur,mid,r,pos*2+2,delta);
    segtree[pos] = min(segtree[pos*2+1],segtree[pos*2+2]);
}

void queryrange(int ql,int qr,int l,int r,int pos){
    if(l >= r) return ;
    if(lazy[pos] != 0){
        segtree[pos] += lazy[pos];
        if(r-l != 1){
            lazy[2*pos+1] += lazy[pos];
            lazy[2*pos+2] += lazy[pos];
        }
        lazy[pos] = 0;
    }
    if(ul >= r || ur <= l) return INF;
    if(ul <= l && ur >= r) return segtree[pos];

    int mid = (r+l) / 2;
    return min(queryrange(ql,qr,l,mid,pos*2+1),queryrange(ql,qr,mid,r,pos*2+2)); 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值