您的位置:首页 > 其它

树——主席树

2015-08-23 21:16 344 查看
参考博客——http://blog.finaltheory.info/algorithm/Chairman-Tree.html#

主席数是一种离线树,用来查询l到r之间的第k最大/最小值的数据结构

是一种函数式编程思想,即不断赋值,更新状态

1.建树

我们对于每一个节点都建一颗线段树,因为对于每一个节点建树,如果不进行优化复杂度会到n^2logn,在这里面会有很多节点是重复的,所以我们要有效的利用这些过去状态的节点。

那么我们就得到root[i]的定义:从加入第一个点到加入i个点之后的区间

每次进行操作,都是在一颗 线段树更新一条链,那么当所有都处理完,就可以得到1到n状态的线段树,利用线段树结构相似区间能够相减的性质就能够得到答案

2.查询

对于每次查询,根据线段树形态相似的性质,二分找区间,如果mid <= k 那么说明在左边就可以找到了,如果mid > k 那么我们在右边找k-sum这么长的区间

模拟思路很清晰



主席数离线询问操作

/************************************************
* Author        :Powatr
* Created Time  :2015-8-23 19:12:05
* File Name     :主席数.cpp
************************************************/

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <cstdlib>
#include <ctime>
using namespace std;

typedef long long ll;
const int MAXN = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;

struct edge{
int sum, lson, rson;
}classtree[MAXN<<5];
int cnt = 0;
int root[MAXN];
int a[MAXN], b[MAXN];
int Createnode(int sum, int lson, int rson)
{
int id = ++cnt;
classtree[id].sum = sum ;
classtree[id].lson = lson;
classtree[id].rson = rson;
return id;
}
void insert(int &rt, int pre_rt, int pos, int l, int r)
{
rt = Createnode(classtree[pre_rt].sum + 1, classtree[pre_rt].lson, classtree[pre_rt].rson);
if(l == r) return ;
int mid = l + r >> 1;
if(pos <= mid)
insert(classtree[rt].lson,classtree[pre_rt].lson, pos, l , mid);
else insert(classtree[rt].rson, classtree[pre_rt].rson, pos, mid + 1, r);
}

int query(int l_rt, int r_rt, int l, int r, int k)
{
if(l == r) return l;
int mid = l + r >> 1;
int sum = classtree[classtree[r_rt].lson].sum - classtree[classtree[l_rt].lson].sum ;
if(k <= sum)
return query(classtree[l_rt].lson, classtree[r_rt].lson, l, mid, k);
else return query(classtree[l_rt].rson, classtree[r_rt].rson, mid+1, r, k - sum);
}

int main(){
int n, m;
int T;
for(scanf("%d", &T); T--; ){
scanf("%d%d", &n, &m);
cnt = 0;
memset(root, 0, sizeof(root));
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
b[i] = a[i];
}
sort(b + 1, b + n + 1);
int num = unique(b + 1, b + n + 1) - (b + 1);
for(int i = 1; i <= n; i++){
int pos = lower_bound(b + 1, b + num + 1, a[i]) - b;
insert(root[i], root[i-1], pos, 1, num);
}
int l, r, k;
while(m--){
scanf("%d%d%d", &l, &r, &k);
int f_pos = query(root[l-1] , root[r], 1, num, k);
printf("%d\n", b[f_pos]);
}
}
return 0;
}


主席数离线更新操作——待更新
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: