POJ 1442 Black Box(treap树指针实现)

题目链接:点击打开链接

思路:本来不想用指针实现的, 但是在做动态第K小的题目时发现, 如果不用动态申请内存的方式, 数组根本开不下。

思路和静态数组模拟是一样的。

细节参见代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <bitset>
#include <cstdlib>
#include <cmath>
#include <set>
#include <list>
#include <deque>
#include <map>
#include <queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
typedef long double ld;
const ld eps = 1e-9, PI = 3.1415926535897932384626433832795;
const int mod = 1000000000 + 7;
const int INF = 0x3f3f3f3f;
// & 0x7FFFFFFF
const int seed = 131;
const ll INF64 = ll(1e18);
const int maxn = 3e4 + 10;
int T,n,m,a[maxn];
struct node {
    node *ch[2];
    int r, v, s;

    int cmp(int x) const {
        if(x == v) return -1;
        return x < v ? 0 : 1;
    }
    void maintain() {
        s = 1;
        if(ch[0] != NULL) s += ch[0]->s;
        if(ch[1] != NULL) s += ch[1]->s;
    }
} *g, *top, Node[maxn];
node *newnode(int x) {
    top -> v = x ;
    top -> s = 1 ;
    top -> r = rand () ;
    top -> ch[0] = top -> ch[1] = NULL ;
    return top ++ ;
}
void rotate(node* &o, int d) {
    node* k = o->ch[d^1];  //旋转, 使得优先级满足堆的意义
    o->ch[d^1] = k->ch[d];
    k->ch[d] = o;
    o->maintain();
    k->maintain();
    o = k;
}
void insert(node* &o, int x) {
    if(o == NULL) o = newnode(x);
    else {
        int d = (x < o->v ? 0 : 1);
        insert(o->ch[d], x);
        if(o->ch[d]->r > o->r) rotate(o, d^1);
    }
    o->maintain();
}
void remove(node* &o, int x) {
    int d = o->cmp(x);
    if(d == -1) {
        node* u = o;
        if(o->ch[0] != NULL && o->ch[1] != NULL) {
            int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0);
            rotate(o, d2);
            remove(o->ch[d2], x);
        }
        else {
            if(o->ch[0] == NULL) o = o->ch[1];
            else o = o->ch[0];
            delete u;
        }
    }
    else remove(o->ch[d], x);
    if(o != NULL) o->maintain();
}
int kth(node* o, int k) {
    if(o == NULL || k <= 0 || k > o->s) return 0;
    int s = (o->ch[0] != NULL ? o->ch[0]->s : 0);

    if(k == s+1) return o->v;
    else if(k <= s) return kth(o->ch[0], k);
    else return kth(o->ch[1], k-s-1);
}
int v;
int main() {
    while(~scanf("%d%d",&n,&m)) {
        for(int i = 1; i <= n; i++) {
            scanf("%d",&a[i]);
        }
        top = Node;
        int cnt = 1;
        for(int i = 1; i <= m; i++) {
            scanf("%d",&v);
            while(v >= cnt) insert(g, a[cnt++]);
            printf("%d\n",kth(g, i));
        }
    }
    return 0;
}



你可能感兴趣的:(poj,treap,ACM-ICPC)