POJ 1442 Black Box 升序询问第k小 优先队列 / Treap

来源:互联网 发布:网络购彩平台贴吧 编辑:程序博客网 时间:2024/05/17 22:12

题目链接

题意

按顺序插入 n 个数,给出 m 个询问,问插入第 bi 个数后序列中的第 i 小数。

法一:优先队列

参考

POJ 1442 Black Box (优先队列) ——lyhvoyage

思路

因为该题中所问的第 k 小数是升序询问的,所以可以用两个优先队列搞一搞,第一个降序(维护最小的 k 个),第二个升序。
注意:每次插入前要使第一个队列尽量满,从而保证第二个队列中的最小值大于第一个中的最大值。

Code

#include <cstdio>#include <iostream>#include <queue>#define maxn 30010using namespace std;priority_queue<int, vector<int>, greater<int> > q2;priority_queue<int> q1;int n, m, a[maxn];void work() {    while (!q1.empty()) q1.pop();    while (!q2.empty()) q2.pop();    for (int i = 0; i < m; ++i) scanf("%d", &a[i]);    int p = 0, k = 1;    while (n--) {        int x;        scanf("%d", &x);        while (q1.size() < k && !q2.empty()) {            q1.push(q2.top());            q2.pop();        }        while (p < x) {            int y = a[p++];            if (q1.size() < k) q1.push(y);            else {                int temp = q1.top();                if (temp <= y) q2.push(y);                else {                    q1.pop();                    q1.push(y);                    q2.push(temp);                }            }        }        ++k;        printf("%d\n", q1.top());    }}int main() {    while (scanf("%d%d", &m, &n) != EOF) work();    return 0;}

法二:Treap

Code

#include <cstdio>#include <climits>#include <cstdlib>#include <ctime>#define maxn 30010using namespace std;int n, m, a[maxn];struct node {    node* ch[2];    int val, key, sz;    node() { sz = 0, key = INT_MAX; }    node(int x);    void update() {        sz = ch[0]->sz + ch[1]->sz + 1;    }}*null = new node;node::node(int x) {    ch[0] = ch[1] = null;    sz = 1, val = x, key = rand();}struct treap {    node* root;    treap() { root = null; }    void rotate(node*& t, bool b) {        node* p = t->ch[b];        t->ch[b] = p->ch[!b];        p->ch[!b] = t;        t->update();        p->update();        t = p;    }    void insert(node*& t, int x) {        if (t == null) {            t = new node(x);            return;        }        bool dir = x > t->val;        insert(t->ch[dir], x);        if (t->ch[dir]->key < t->key) rotate(t, dir);        else t->update();    }    int calckth(int k) {        int dir;        for (node* t = root; t != null; t = t->ch[dir]) {            int cnt = t->ch[0]->sz;            if (k == cnt+1) return t->val;            else if (k <= cnt) dir = 0;            else dir = 1, k -= (cnt+1);        }    }    void insert(int x) { insert(root, x); }    int size() { return root->sz; }};void work() {    treap* Treap = new treap;    for (int i = 0; i < m; ++i) scanf("%d", &a[i]);    int p = 0, k = 1;    while (n--) {        int x;        scanf("%d", &x);        while (p < x) {            int y = a[p++];            Treap->insert(y);        }        printf("%d\n", Treap->calckth(k));        ++k;    }}int main() {    while (scanf("%d%d", &m, &n) != EOF) work();    return 0;}
原创粉丝点击