struct Node {
int pri, data, num, sz, ch[2], fa;
}t[maxn];
int pos;
struct Treap {
int root;
int newNode(int x) {
t[++ pos] = (Node){rand(), x, 1, 1, 0, 0, 0};
return pos;
}
void update(int x) {
t[x].sz = t[t[x].ch[0]].sz + t[t[x].ch[1]].sz + t[x].num;
}
int locate(int x) {
return x == t[t[x].fa].ch[1];
}
void rotate(int x){
int y = t[x].fa, z = t[y].fa, p = locate(x);
t[y].ch[p] = t[x].ch[p ^ 1], t[x].ch[p ^ 1] = y, t[t[y].ch[p]].fa = y;
t[x].fa = t[y].fa, t[y].fa = x;
update(y), update(x);
if (z) {
t[z].ch[t[z].ch[1] == y] = x;
update(z);
}
}
void maintain(int x) {
while (x) {
update(x);
x = t[x].fa;
}
}
void insert(int data) {
if (root == 0) {
root = newNode(data);
return ;
}
int x = root;
while (true) {
if (t[x].data == data){
t[x].num ++;
break;
}
int p = data > t[x].data;
if (!t[x].ch[p]) {
t[x].ch[p] = newNode(data);
t[t[x].ch[p]].fa = x;
x = t[x].ch[p];
break;
}
x = t[x].ch[p];
}
maintain(x);
while (t[x].fa && t[t[x].fa].pri < t[x].pri)
rotate(x);
if (t[x].fa == 0)
root = x;
}
int get_pos(int data) {
int x = root;
while (true) {
if (t[x].data == data)
return x;
int p = data > t[x].data;
x = t[x].ch[p];
}
return x;
}
void del(int data) {
int x = get_pos(data);
if (t[x].num > 1){
t[x].num --;
maintain(x);
return ;
}
while (t[x].ch[0] + t[x].ch[1]) {
int p = t[t[x].ch[1]].pri > t[t[x].ch[0]].pri;
rotate(t[x].ch[p]);
if (t[t[x].fa].fa == 0)
root = t[x].fa;
}
t[x].num = 0;
maintain(x);
t[t[x].fa].ch[locate(x)] = 0;
t[x].fa = 0;
if (root == x)
root = 0;
}
int rks(int data) {
int x = root;
int res = 0;
while (true) {
if (t[x].data == data)
return res + t[t[x].ch[0]].sz + 1;
if (t[x].data < data)
res += t[x].num + t[t[x].ch[0]].sz;
x = t[x].ch[(data > t[x].data)];
}
}
int kth(int k) {
int x = root;
while (x) {
if (t[t[x].ch[0]].sz >= k)
x = t[x].ch[0];
else if (t[x].num + t[t[x].ch[0]].sz >= k)
return t[x].data;
else k -= t[x].num + t[t[x].ch[0]].sz, x = t[x].ch[1];
}
}
int pre(int data) {
int x = root, ans;
while (x) {
if (t[x].data < data)
ans = t[x].data, x = t[x].ch[1];
else x = t[x].ch[0];
}
return ans;
}
int suf(int data) {
int x = root, ans;
while (x) {
if (t[x].data > data)
ans = t[x].data, x = t[x].ch[0];
else x = t[x].ch[1];
}
return ans;
}
}treap;
标签:ch,return,fa,int,root,代码,Treap,data,模板
From: https://www.cnblogs.com/yh2021shx/p/17469855.html