您的位置:首页 > 其它

poj 1442 Black box (Treap过~)

2017-10-26 11:06 375 查看
看到有各种为了让树更加平衡的操作,于是用treap解决了这个题

(POJ进不去,偶也不知道解决没,反正选了一种模板照着写的)

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>

using namespace std;

#define MX 30010

int size, root;
struct Node {
int l, r, key, rand_fix;
int countl, countr;
} node[MX];
void Treap_left_rotate(int &index) {
int y = node[index].r;
node[index].r = node[y].l;
node[index].countr = node[y].countl;
node[y].l = index;
node[y].countl = node[index].countr + node[index].countr + 1;
index = y;
}

void Treap_right_rotate(int &index) {
int y = node[index].l;
node[index].l = node[y].r;
node[index].countl = node[y].countr;
node[y].r = index;
node[y].countr = node[index].countl + node[index].countl + 1;
index = y;
}

void Treap_insert(int &index, int x) {
if (index == -1) {
index = ++size;
node[index].l = node[index].r = -1;
node[index].rand_fix = rand();
node[index].key = x;
node[index].countl = node[index].countr = 0;
return;
}

if (x < node[index].key) {
node[index].countl++;
Treap_insert(node[index].l, x);
if (node[node[index].l].rand_fix < node[index].rand_fix)
Treap_right_rotate(index);
} else {
node[index].countr++;
Treap_insert(node[index].r, x);
if (node[node[index].r].rand_fix < node[index].rand_fix)
Treap_left_rotate(index);
}
}

int find(int index, int count) {
if (index == -1) return -1;

if (node[index].countl + 1 == count) return node[index].key;

if (node[index].l == -1) return find(node[index].r, count - 1);

if (node[index].countl + 1 < count)
return find(node[index].r, count - (node[index].countl + 1));
else
return find(node[index].l, count);
}

int m, n;
int main(void) {
int data[MX], t, inc = 0;
size = root = -1;
scanf("%d%d", &m, &n);
int c = 0;

for (int i = 0; i < m; i++) scanf("%d", &data[i]);
for (int i = 0; i < n; i++) {
scanf("%d", &t);
while (c < t) Treap_insert(root, data[c++]);
printf("%d\n", find(root, ++inc));
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: