首页 > 代码库 > 可持久化线段树(主席树)模板

可持久化线段树(主席树)模板

比赛时候写的,这里整理到这里

 

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 2e5 + 500;
struct Node{
    Node *l, *r;
    int v;
    void maintain(){
        v = l->v + r->v;
    }
}pool[maxn*16], *root[maxn], *null;
int tot = 0;
Node *newnode(){
    Node* temp = &pool[tot++];
    temp->l = temp->r = null; temp->v = 0;
    return temp;
}
void init(){
    null = new Node();
    null->l = null->r = null;
    null->v = 0;
}
void Insert(Node *&o, Node *o2, int l, int r, int k, int v){
    if(o == null) o = newnode();
    if(l == r) { o->v += v + o2->v; return; }
    int mid = (l+r)/2;
    if(k <= mid) {
        Insert(o->l, o2->l, l, mid, k, v);
        o->r = o2->r;
    } else {
        Insert(o->r, o2->r, mid+1, r, k, v);
        o->l = o2->l;
    }
    o->maintain();
}
int Query(Node *o, int l, int r, int L, int R){
    if(o == null) return 0;
    if(L <= l && r <= R) return o->v;
    int mid = (l+r)/2, ans = 0;
    if(L <= mid) ans += Query(o->l, l, mid, L, R);
    if(R > mid) ans += Query(o->r, mid+1, r, L, R);
    return ans;
}

int main(){
    return 0;
}

 

可持久化线段树(主席树)模板