POJ

来源:互联网 发布:淘宝模特基本动作 编辑:程序博客网 时间:2024/05/21 07:13

You are working for Macrohard company in data structures department. After failing your previous task about key insertion you were asked to write a new data structure that would be able to return quickly k-th order statistics in the array segment.
That is, given an array a[1…n] of different integer numbers, your program must answer a series of questions Q(i, j, k) in the form: “What would be the k-th number in a[i…j] segment, if this segment was sorted?”
For example, consider the array a = (1, 5, 2, 6, 3, 7, 4). Let the question be Q(2, 5, 3). The segment a[2…5] is (5, 2, 6, 3). If we sort this segment, we get (2, 3, 5, 6), the third number is 5, and therefore the answer to the question is 5.
Input
The first line of the input file contains n — the size of the array, and m — the number of questions to answer (1 <= n <= 100 000, 1 <= m <= 5 000).
The second line contains n different integer numbers not exceeding 10 9 by their absolute values — the array for which the answers should be given.
The following m lines contain question descriptions, each description consists of three numbers: i, j, and k (1 <= i <= j <= n, 1 <= k <= j - i + 1) and represents the question Q(i, j, k).
Output
For each question output the answer to it — the k-th number in sorted a[i…j] segment.
Sample Input
7 3
1 5 2 6 3 7 4
2 5 3
4 4 1
1 7 3
Sample Output
5
6
3


题意:区间第K大

solution:主席树

#include <cstdio>#include <iostream>#include <cstring>#include <algorithm>using namespace std;#define N 100007struct Node{    int l, r, ls, rs, sum;}tree[N<<5];int a[N], b[N];int rt[N], pos, cnt;void build( int &nd, int l, int r ){    nd=++cnt;    tree[nd].l=l, tree[nd].r=r;    if( l==r ) return ;    int mid=(l+r)>>1;    build(tree[nd].ls,l,mid);    build(tree[nd].rs,mid+1,r);} void insert( int pre, int &nd ){    nd=++cnt;    tree[nd]=tree[pre];    tree[nd].sum++;    int mid=(tree[nd].l+tree[nd].r)>>1;    if( tree[nd].l==tree[nd].r ) return ;    if( pos<=mid ) insert( tree[pre].ls, tree[nd].ls );    else insert( tree[pre].rs, tree[nd].rs );} int query( int pre, int nd, int k ){    if( tree[nd].ls==tree[nd].rs ) return b[tree[nd].l];    int cmp=tree[tree[nd].ls].sum-tree[tree[pre].ls].sum;    if( cmp>=k ) return query( tree[pre].ls, tree[nd].ls, k );    else return query( tree[pre].rs, tree[nd].rs, k-cmp);}int main(){    int n, q;    scanf("%d%d", &n, &q );    cnt=0;    for ( int i=1; i<=n; b[i]=a[i], i++ ) scanf("%d", &a[i] );    sort(b+1,b+1+n);    build(rt[0],1,n);    for ( int i=1; i<=n; i++ ){        pos=lower_bound( b+1, b+1+n, a[i] )-b;        insert(rt[i-1],rt[i]);    }    while( q-- ){        int l, r, k;        scanf("%d%d%d", &l, &r, &k );        printf("%d\n", query(rt[l-1],rt[r],k) );    }    return 0;}
原创粉丝点击