hdu Kth number

Problem Description
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
 

Source
 

Recommend
zty   |   We have carefully selected several similar problems for you:  2660 2662 2667 2663 2661

题意:找第k大的数

可持久化线段树。
和普通线段树不同的地方是:可持久化线段树可以找到之前做过的某种状态。
可持久化线段树的讲解这个博客比较好:http://blog.sina.com.cn/s/blog_4a0c4e5d0101c8fr.html
这道题就是维护一颗权值线段树(其实知道权值线段树后这题就很简单了),来实现找k大的操作。

可持久化线段树模板题。。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int ls[maxn * 20], rs[maxn * 20], sum[maxn * 20];
int T[maxn],tot,rt;
void build(int l,int r,int &rt) 
{
    rt = ++ tot;
    sum[rt] = 0;
    if(l == r) return;
    int mid = (l + r) >> 1;
    build(l, mid, ls[rt]);
    build(mid + 1, r, rs[rt]);
}
void update(int last,int p,int l,int r,int &rt)
{
    rt = ++ tot;
    ls[rt]  = ls[last];
    rs[rt]  = rs[last];
    sum[rt] = sum[last] + 1;
    if(l == r) return;
    int mid = (l + r) >> 1;
    if(p <= mid) update(ls[last], p, l, mid, ls[rt]);
    else update(rs[last], p, mid + 1, r, rs[rt]);
}
int query(int ss,int tt,int l,int r,int k)
{
    if(l == r) return l;
    int mid = (l + r) >> 1;
    int cnt = sum[ls[tt]] - sum[ls[ss]];
    if(k <= cnt) return query(ls[ss], ls[tt], l, mid, k);
    else return query(rs[ss], rs[tt], mid + 1, r, k - cnt);
}
int num[maxn],san[maxn],n,m;
int main()
{
    int t;
	scanf("%d",&t);
	for(int Z = 1; Z <= t; Z ++)
	{
	    scanf("%d%d",&n, &m);
	    int l,r,k;
	    for(int i = 1; i <= n; i ++)
	    {
	        scanf("%d",&num[i]);
	        san[i] = num[i];
	    }
	    tot = 0;
	    sort(san + 1, san + n + 1);
	    int cnt = unique(san + 1, san + n + 1) - san - 1;
	    build(1, cnt, T[0]);
	    for(int i = 1; i <= n; i ++) num[i] = lower_bound(san + 1, san + cnt + 1, num[i]) - san;
	    for(int i = 1; i <= n; i ++) update(T[i - 1], num[i], 1, cnt, T[i]);
	    for(int i = 1; i <= m; i ++)
	    {
	        scanf("%d%d%d",&l,&r,&k);
	        int id = query(T[l - 1], T[r], 1, cnt, k);
	        printf("%d\n",san[id]);
	    }
	}
    return 0;
}


 
全部评论

相关推荐

投递阿里巴巴控股集团等公司10个岗位 >
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务