主席树是基于权值线段树的一种数据结构,最经典的应用便是处理静态区间第k大
建点
int newNode(int x){
top++;
tree[top] = tree[x];
tree[top].val++;
return top;
}
建树
int build(int l,int r){
int now = ++top;
tree[now].val = 0;
if(l == r)return now;
int mid = (l + r) >> 1;
tree[now].l = build(l,mid);
tree[now].r = build(mid + 1,r);
return now;
}
修改
int update(int pre,int l,int r,int x){
int now = newNode(pre);
if(l >= r)return now;
int mid = (l + r) >> 1;
if(x <= mid)tree[now].l = update(tree[pre].l,l,mid,x);
else tree[now].r = update(tree[pre].r,mid + 1,r,x);
return now;
}
查询
int query(int x,int y,int l,int r,int k){
if(l >= r)return l;
int val = tree[tree[y].l].val - tree[tree[x].l].val;
int mid = (l + r) >> 1;
if(val >= k)return query(tree[x].l,tree[y].l,l,mid,k);
else return query(tree[x].r,tree[y].r,mid + 1,r,k - val);
}