劃分樹——求區間第k大值

來源:互聯網
上載者:User

題目:K-th Number

雖說是第一次就AC,但到網上去搜羅更優代碼時,卻幸運的發現,我的AC代碼是錯誤的,只不過資料太水。我考慮掉一種情況,當有多個數和中位元相同時,如果從左至右一次將小於等於中位元的數劃入左子樹,可能導致區間右端的哪些比中位元小的數被劃入右子樹。例如,資料為1 2 2 2 1時,第二個2應劃入右子樹,最後一個1應劃入左子樹。

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define MAXN 100010#define lson l,m,d+1#define rson m+1,r,d+1int a[20][MAXN],sorted[MAXN],toLeft[20][MAXN];void build(int l,int r,int d) {    if(l==r) return ;    int m=(l+r)>>1,p1=l-1,p2=m;    int mv=sorted[m];    if(l==1) toLeft[d][0]=0;    int lsame=m-l+1;    for(int i=l;i<=r;++i) if(a[d][i]<mv) --lsame;//找出左子樹可容納多少中位元    for(int i=l;i<=r;++i) {        toLeft[d][i]=toLeft[d][i-1];        if(a[d][i]<mv) ++toLeft[d][i],a[d+1][++p1]=a[d][i];        else if(a[d][i]>mv) a[d+1][++p2]=a[d][i];        else {            if(lsame) ++toLeft[d][i],a[d+1][++p1]=a[d][i],--lsame;//左子樹還可容納中位元            else a[d+1][++p2]=a[d][i];        }    }    build(lson);    build(rson);}int query(int k,int x,int y,int l,int r,int d) {    if(l==r) return sorted[l];    int l1=toLeft[d][x-1]-toLeft[d][l-1],l2=toLeft[d][y]-toLeft[d][x-1];//l1=[l,x-1]上劃入左子樹的數目,l2=[x,y]上劃入左子樹的數目    int m=(l+r)>>1;    int r1=x-l-l1,r2=y-x+1-l2;//r1=[l,x-1]上劃入右子樹的數目,r2=[x,y]上劃入右子樹的數目    if(k<=l2) return query(k,l+l1,l+l1+l2-1,lson);    else return query(k-l2,m+1+r1,m+r1+r2,rson);}int main() {    ios::sync_with_stdio(false);    int n,m;    cin >> n >> m;    for(int i=1;i<=n;++i) cin >> a[1][i],sorted[i]=a[1][i];    sort(sorted+1,sorted+1+n);    build(1,n,1);    while(m--) {        int a,b,k;        cin >> a >> b >> k;        cout << query(k,a,b,1,n,1) << endl;    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.