Double Queue 【POJ - 3481】【Splay】

题目链接


  这道题很多人会想到用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;
}

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值