【樹狀數組求第k小】POJ 2892

來源:互聯網
上載者:User

又一次用到樹狀數組求第k小,注意邊界情況

#define N 50005int c[N];int lowbit(int x){    return x&(-x);}void add(int x,int v){    while(x<N){        c[x]+=v;        x+=lowbit(x);    }}int sum(int x){    int ans = 0;    while(x){        ans+=c[x];        x-=lowbit(x);    }    return ans;}int find_k(int k){    int ans=0,cnt=0;    for(int i=log(double(N-1))/log(2.0);i>=0;i--){        ans += (1<<i);        if(ans>=N || cnt+c[ans]>=k){            ans-=(1<<i);        } else cnt+=c[ans];    }    return ans+1;}int main(){    int n,m;    while(scanf("%d%d",&n,&m)!=-1){        int i,j;        memset(c,0,sizeof(c));        stack<int> st;        add(1,1);//注意邊界,都往後移一位        add(n+2,1);//同上        while(m--){            char str[2];            scanf("%s",str);            int pos;            if(str[0]=='D'){                scanf("%d",&pos);                pos++;                add(pos,1);                st.push(pos);            } else if(str[0]=='R'){                pos = st.top();st.pop();                add(pos,-1);            } else {                scanf("%d",&pos);                pos++;                int k = sum(pos);                int a = find_k(k);                int b = find_k(k+1);                if(k-sum(pos-1)==1){                    printf("0\n");                } else printf("%d\n",b-a-1);            }        }    }    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.