【POJ 2104】(K-th Number-区间第k大-主席树)

POJ 2104(K-th Number-区间第k大-主席树)
!裸题
1.Hash后建树;
2.x-y区间最大—-》sum[y]-sum[x-1]后贪心去找;
3.建树时需1-i(n=>i>=1)的树, 【可持久化】—–》改rson 则lson等;

#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
int tot=0;
int n;
int m;
int a[200010];
int sa[200010];
int gg[200010];
int cmp(int x,int y)
{
    return x<y;
}
struct node{
    int ls,rs,val;
}tree[200010*20];
int build(int l,int r)
{
    int tmp=++tot;
    tree[tmp].val=0;
    if(l==r) return tmp;    
    int mid=(l+r)>>1;
    tree[tmp].ls=build(l,mid);
    tree[tmp].rs=build(mid+1,r);
    return tmp;
}
int add(int y,int l,int r,int pos,int V)
{
    int tmp=++tot;
    tree[tmp]=tree[y];
    tree[tmp].val+=V;   
    if(l==r) return tmp;
    int mid=(l+r)>>1;
    if(pos<=mid)   tree[tmp].ls=add(tree[y].ls,l,mid,pos,V);
        else tree[tmp].rs=add(tree[y].rs,mid+1,r,pos,V);
    return tmp;
}
int query(int x,int y,int l,int r,int pos)
{
    //cout<<l<<" "<<r<<" "<<pos<<" "<<tree[tree[y].ls].val<<" "<<tree[tree[x].ls].val<<" "<<endl;
    if(l==r) return  l;
    int mid=(l+r)>>1;
    int tmp=tree[tree[y].ls].val-tree[tree[x].ls].val;

    if(pos<=tmp)
    return query(tree[x].ls,tree[y].ls,l,mid,pos);
    else return query(tree[x].rs,tree[y].rs,mid+1,r,pos-tmp);
}


int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{   
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        sa[i]=a[i];
    }   
    sort(sa+1,sa+1+n,cmp);    //hash1
    int nn=0;
    for(int i=1;i<=n;i++)
    {
        if(i==1||sa[i]!=sa[nn])
        sa[++nn]=sa[i];
    }   
    gg[0]=build(1,nn);
    for(int i=1;i<=n;i++)
    {
        int p=lower_bound(sa+1,sa+1+n,a[i])-sa;  //hash2
        gg[i]=add(gg[i-1],1,nn,p,1);
    }
    for(int i=1;i<=m;i++)   
    {
        int aa,bb,cc;
        scanf("%d%d%d",&aa,&bb,&cc);
        printf("%d\n",sa[query(gg[aa-1],gg[bb],1,nn,cc)]);
    }
}
}

你可能感兴趣的:(namespace,poj,可持久化线段)