poj 2104 主席树模板题,无修改区间第 k大

K-th Number

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<bitset>
#include<vector>
#include<set>
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
#define rep(i,a,b) for (int i=a; i<=b; ++i)
#define per(i,b,a) for (int i=b; i>=a; --i)
#define mes(a,b)  memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define MP make_pair
#define PB push_back
#define fi  first
#define se  second
typedef long long ll;

const int N = 100005;
#define mid  (l+(r-l)/2)
int root[N], cnt;
struct Tree { int l, r, sum; } T[N*40];
void update(int l, int r, int &x, int y, int pos) {
    T[++cnt]=T[y],  ++T[cnt].sum,  x=cnt;
    if(l==r) return ;
    if(pos<=mid) update(l, mid, T[x].l, T[y].l, pos);
    else  update(mid+1, r, T[x].r, T[y].r, pos);
}
int query(int l, int r, int x, int y, int k) {
    if(l==r) return l;
    int sum = T[T[y].l].sum - T[T[x].l].sum;
    if(k<=sum) return query(l, mid, T[x].l, T[y].l, k);
    else  return query(mid+1, r, T[x].r, T[y].r, k-sum);
}
int n, m, a[N];
vector< int > ve;
int getId(int x) {
    return lower_bound(ve.begin(), ve.end(), x) - ve.begin() + 1;
}
int main()
{
    scanf("%d%d", &n, &m);
    rep(i,1,n) scanf("%d", &a[i]), ve.PB(a[i]);
    sort(ve.begin(), ve.end());
    ve.erase(unique(ve.begin(), ve.end()), ve.end());
    rep(i,1,n) update(1, n, root[i], root[i-1], getId(a[i]));
    int x, y, k;
    while(m--)
    {
        scanf("%d%d%d", &x, &y, &k);
        printf("%d\n", ve[query(1, n, root[x-1], root[y], k)-1]);
    }

    return 0;
}
posted @ 2018-04-13 15:52  v9fly  阅读(96)  评论(0编辑  收藏  举报