zoukankan      html  css  js  c++  java
  • poj1442(treap求第k大)

    ac代码:

    #include<bits/stdc++.h>
    using namespace std;
    #define per(i,a,b) for(int i=a;i <= b;i++)
    #define Max(a,b) a=max(a,b)
    #define Min(a,b) a=min(a,b)
    #define Sz(x) (int)x.size()
    typedef long long ll;
    ll gcd(ll a,ll b){while(b){ll t=b;b=a%b;a=t;} return a;}
    const int inf=0x3f3f3f3f;
    #define siz 30005
    int m,n,num[siz],qr[siz],ord;
    struct TreapNode
    {
        int rnd,sz;
        TreapNode*child[2];
        int v;
        TreapNode(int val):v(val){
            rnd=rand();
            child[0]=child[1]=NULL;
            sz=1;
        }
        void update(){sz=1; if(child[0]!=NULL)sz+=child[0]->sz; if(child[1]!=NULL)sz+=child[1]->sz;}
    }*root,*tmp;
    void Rotate(TreapNode*&u,int type)
    {
        tmp=u->child[type^1];
        u->child[type^1]=tmp->child[type];
        tmp->child[type]=u;
        u->update();
        u=tmp;
        u->update();
    }
    void Insert(TreapNode*&u,int val)
    {
        if(u==NULL){
            u=new TreapNode(val);
        }
        else {
            int type=val > u->v;
            Insert(u->child[type],val);
            if(u->child[type]->rnd > u->rnd)Rotate(u,type^1);
        }
        u->update();
    }
    void k_th(TreapNode*u,int k)//按照ord的数字找
    {
        if(k==1&&u->child[0]==NULL){printf("%d
    ",u->v);return;}
        if(u->child[0]==NULL)return k_th(u->child[1],k-1);
        if(u->child[0]->sz == k-1){
            printf("%d
    ",u->v);
            return;
        }
        if(u->child[0]->sz < k-1)return k_th(u->child[1],k - u->child[0]->sz - 1);
        else if(u->child[0]->sz > k-1)return k_th(u->child[0],k);
    }
    void Print(TreapNode*u)
    {
        if(u==NULL)return;
        Print(u->child[0]);
        printf("%d ",u->v);
        Print(u->child[1]);
    }
    
    int main()
    {
        std::ios::sync_with_stdio(false);
        root=tmp=NULL;
        while(scanf("%d %d",&m,&n)!=EOF){
            ord=0;
            per(i,1,m)scanf("%d",&num[i]);
            qr[0]=0;
            for(int i=1;i<=n;i++){
                scanf("%d",&qr[i]);
                for(int j=qr[i-1]+1;j<=qr[i];j++){
                    Insert(root,num[j]);
                    //printf("root:%d  ",root->v);Print(root);printf("
    ");
                }
                ord++;
                k_th(root,ord);
            }
        }
    
        return 0;
    }
    
    /*
    9 5
    5 2 1 4 8 6 3 9 7
    1 3 5  9 9
    */
  • 相关阅读:
    案例分析:从一则笑话分析需求的陷阱
    2019寒假培训第二天
    2019寒假培训第一天
    牛客网国庆集训派对Day6 题目 2018年
    unique STL讲解和模板
    SPFA 模板
    ACM Shenyang Onsite 2016 题目
    牛客网国庆集训派对Day5 题目 2018年
    The North American Invitational Programming Contest 2017 题目
    牛客网国庆集训派对Day4题目 2018年
  • 原文地址:https://www.cnblogs.com/WindFreedom/p/9379674.html
Copyright © 2011-2022 走看看