【Treap】poj1442 Black Box

七月了。NOI也结束了。


题目点这里

题意:有个黑箱子。有两个数组A[1...N] Q[1...M] 其中A数组表示依次往黑箱子里加入A[i]这个数 Q[i]表示在加入了A[Q[i]]以后查询箱子里第i大的数


正解大概不是treap。。不过也就80行。。。


#include <cstdio>
#include <iostream>
#include <cstdlib>

using namespace std;

const int Nmax = 30005;

int N, M;
int A[Nmax], Q[Nmax];

namespace Treap {
    struct Node {
        Node *lc, *rc;
        int s, w, r;
    }T[Nmax], *root, *null;
    int cnt = 0;
    
    Node *NewNode(int x = 0) {
        T[cnt].lc = T[cnt].rc = null;
        T[cnt].s = 1; T[cnt].w = x; T[cnt].r = rand();
        return &T[cnt++];
    }
    
    void init() {
        cnt = 0; null = NewNode(); null -> s = 0; null -> r = -1;
        root = null; 
    }
    
    inline void pushup(Node *&p) { p->s = p->lc->s + p->rc->s + 1; }
    
    inline void maintain(Node *&p) {
        if(p->lc->r > p->r) {
            Node *temp = p -> lc;
            p -> lc = temp -> rc;
            temp -> rc = p;
            pushup(p); p = temp;
        }
        else if(p->rc->r > p->r) {
            Node *temp = p -> rc;
            p -> rc = temp -> lc;
            temp -> lc = p;
            pushup(p); p = temp;
        }
        pushup(p);
    }
    
    void insert(Node *&p, int x) {
        if (p == null) {
            p = NewNode(x);
            return;
        }
        if (p->w > x) insert(p -> lc, x);
        else insert(p -> rc, x);
        maintain(p);
    }
    
    int kth(Node *p, int k) {
        int rank = p -> lc -> s + 1;
        if (rank == k) return p -> w;
        if (rank > k) return kth(p -> lc, k);
        return kth(p -> rc, k - rank);
    }
}

int main()
{
    srand(20150233);
    while (~scanf("%d%d", &N, &M)) {
        for (int i = 1; i <= N; ++ i) scanf("%d", A + i);
        for (int i = 1; i <= M; ++ i) scanf("%d", Q + i);
        using namespace Treap; init(); int p = 1, q = 1;
        for (int i = 1; i <= N; ++ i) {
            insert(root, A[i]);
            for ( ; Q[p] == i; ++ p) printf("%d\n", kth(root, q ++));
        }
    }
    
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值