题目链接
这道题很多人会想到用set来解,当然是可以的,但是确实也可以写splay,因为可以用splay代替set来做到找到某个值,这里我们只需要找到最值问题去求解即可。然后我们对应的找到其与其父亲节点之间的关系,然后更新,就可以做到删除的操作了。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 1e6 + 7;
int root, tot;
struct node
{
int ff, val, siz, ch[2], num;
}t[maxN];
void Rotate(int x)
{
int y = t[x].ff, z = t[y].ff;
int k = t[y].ch[1] == x;
t[z].ch[t[z].ch[1] == y] = x;
t[x].ff = z;
t[y].ch[k] = t[x].ch[k^1];
t[t[x].ch[k^1]].ff = y;
t[x].ch[k^1] = y;
t[y].ff = x;
}
void Splay(int x, int goal)
{
int y, z;
while(t[x].ff != goal)
{
y = t[x].ff; z = t[y].ff;
if(z != goal) ( t[z].ch[0] == y ) ^ ( t[y].ch[0] == x ) ? Rotate(x) : Rotate(y);
Rotate(x);
}
root = x;
}
void insert(int k, int p) //p是优先级,k是价值
{
int u = root, ff = 0;
while(u && t[u].val != p)
{
ff = u;
u = t[u].ch[p > t[u].val];
}
u = ++tot;
if(ff) t[ff].ch[p > t[ff].val] = u;
t[u].ch[0] = t[u].ch[1] = 0;
t[u].ff = ff;
t[u].val = p;
t[u].num = k;
t[u].siz = 1;
Splay(u, 0);
}
int Get_maxx(int u)
{
while(t[u].ch[1]) u = t[u].ch[1];
if(u == root) root = t[u].ch[0];
int y = t[u].ff;
t[y].ch[1] = t[u].ch[0];
t[t[u].ch[0]].ff = y;
return t[u].num;
}
int Get_minn(int u)
{
while(t[u].ch[0]) u = t[u].ch[0];
if(u == root) root = t[u].ch[1];
int y = t[u].ff;
t[y].ch[0] = t[u].ch[1];
t[t[u].ch[1]].ff = y;
return t[u].num;
}
int main()
{
root = tot = 0;
int op, k, p;
while(scanf("%d", &op) && op)
{
if(op == 1)
{
scanf("%d%d", &k, &p);
insert(k, p);
}
else if(op == 2)
{
printf("%d\n", Get_maxx(root));
}
else
{
printf("%d\n", Get_minn(root));
}
}
return 0;
}