HDU - 2665 Kth number (主席树经典题,求区间第K小)
题目
Give you a sequence and ask you the kth big number of a inteval.
Input
The first line is the number of the test cases.
For each test case, the first line contain two integer n and m (n, m <= 100000), indicates the number of integers in the sequence and the number of the quaere.
The second line contains n integers, describe the sequence.
Each of following m lines contains three integers s, t, k.
[s, t] indicates the interval and k indicates the kth big number in interval [s, t]
Output
For each test case, output m lines. Each line contains the kth big number.
Sample Input
1
10 1
1 4 2 3 5 6 7 8 9 0
1 3 2
Sample Output
2
解题思路
题意就是求区间第k小
主席树就是一开始先建一棵普通的线段树,然后一个一个插入,每次插入的时候不动原来的,而是把所有变化的节点都新建一个,连上那些没有变化的节点,这样就相当于有了所有历史版本。
求区间第k小是这样转化的,线段树里记录数字出现的次数,如果要求[l,r]范围内的第k小,首先所有涉及到的数就是l-1和r这两个版本之差,要知道某个区间有多少数只要把对应节点相减就可以了,那么从区间[1,m](m为最大数)开始,每次折半看前半部分有多少数,如果小于k说明第k小在[mid+1,r],否则在[l,mid]。
ps.这道题因为内存限制结构体里不能存范围,只能递归的时候算
AC代码
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const LL maxn=100007;
int n,m;///m为hash后的数据范围
int a[maxn];///初始数据,从1开始
int b[maxn];///hash过的数据
int tree[maxn];///tree[i]为第i个版本的根节点
int tot;///用来表示建了多少节点
struct node
{
int v;///节点值,在此例中为求和
int lc,rc;///左右子树
}t[maxn*22];
void init_hash()
{
for(int i=1;i<=n;i++)
b[i]=a[i];
sort(b+1,b+1+n);
m=unique(b+1,b+1+n)-b-1;
///unique可以把相同元素集中到数组前面,返回最后一个数的后一个位置
}
int get_pos(int x)
{
return lower_bound(b+1,b+1+m,x)-b;
}
int build(int l,int r)
{
int root=tot++;
t[root].v=0;
if(l!=r)
{
int mid=(l+r)/2;
t[root].lc=build(l,mid);
t[root].rc=build(mid+1,r);
}
return root;
}
int update(int root,int l,int r,int x,int v)
{
///每次update生成一个新的节点,是从根到需要更新的那个叶子的路径,其他节点与上一个版本完全相同
int newroot=tot++;
t[newroot]=t[root];
t[newroot].v+=v;
if(l==r)
{
return newroot;
}
int mid=(l+r)/2;
if(x>mid)
{
t[newroot].rc=update(t[root].rc,mid+1,r,x,v);
}
else
{
t[newroot].lc=update(t[root].lc,l,mid,x,v);
}
return newroot;
}
int query(int l,int r,int k,int li,int ri)
{
///l和r分别是两个版本里的相同节点
///li和ri只是用来帮助确定节点表示的范围的
//printf("(%d,%d) %d %d %d\n",li,ri,t[l].v,t[r].v,k);
if(li==ri) return li;
int l1=t[l].lc,l2=t[r].lc;
if(t[l2].v-t[l1].v>=k)
{
return query(l1,l2,k,li,(li+ri)/2);
}
else
{
return query(t[l].rc,t[r].rc,k-t[l2].v+t[l1].v,(li+ri)/2+1,ri);
}
}
//void dfs(int root,int l,int r)
//{
// printf("(%d,%d,%d) ",l,r,t[root].v);
// if(l==r) return;
// int mid=(l+r)/2;
// dfs(t[root].lc,l,mid);
// dfs(t[root].rc,mid+1,r);
//}
int main()
{
int q,T,i,j,k,x,y,l,r;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&q);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
init_hash();
tot=0;
tree[0]=build(1,m);
for(i=1;i<=n;i++)
{
x=get_pos(a[i]);
tree[i]=update(tree[i-1],1,m,x,1);
}
// for(i=0;i<=n;i++)
// {
// dfs(tree[i],1,m);
// printf("\n");
// }
for(i=1;i<=q;i++)
{
scanf("%d%d%d",&l,&r,&k);
x=query(tree[l-1],tree[r],k,1,m);
printf("%d\n",b[x]);
}
}
return 0;
}