POJ2892 Tunnel Warfare (平衡树)

传送门
思路:当炸掉一个城市的时候,就把这个城市放入平衡树中(最开始的时候放入n+1和0),查询的时候输出这个数的后继-前驱-1,这就是答案。

代码(写的Splay):

#include<cstdio>
#define MAXN 50005
struct node {
    int v, ch[2], f;
}t[MAXN];
int rt, sz, n, m;
void rot(int x)
{
    int y = t[x].f, z = t[y].f;
    bool f = (t[y].ch[1] == x);
    t[y].ch[f] = t[x].ch[f^1];
    if(t[y].ch[f]) t[t[y].ch[f]].f = y;
    t[x].ch[f^1] = y; t[y].f = x;
    t[x].f = z;
    if(z) t[z].ch[t[z].ch[1]==y] = x;
}
void Spaly(int r, int tp) {
    for(int y, z; (y = t[r].f) != tp; rot(r)) {
        z = t[y].f;
        if(z == tp) continue;
        if( (t[z].ch[0] == y) == (t[y].ch[0] == r) ) rot(y);
        else rot(r);
    }
    if(!tp) rt = r;
}
void Ins(int r, int x) {
    int y = 0;
    while(r && t[r].v != x) { y = r; r = t[r].ch[x > t[r].v]; }
    r = ++ sz;
    t[r].v = x; t[r].f = y; if(y) t[y].ch[x > t[y].v] = r;
    Spaly(r, 0);
}
void Find(int v) {
    int x = rt; if(!x) return;
    while(t[x].ch[v > t[x].v] && t[x].v != v) x = t[x].ch[v > t[x].v];
    Spaly(x, 0);
}
int Nxt(int x, bool f)
{
    Find(x);
    if((t[rt].v>x&&f)||(t[rt].v<x&&!f)) return rt;
    int p = t[rt].ch[f];
    while(t[p].ch[f^1]) p = t[p].ch[!f];
    return p;
}
void Del(int v) {
    int p = Nxt(v, 0), s = Nxt(v, 1);
    Spaly(p, 0); Spaly(s, p);
    p = t[s].ch[0];
    t[s].ch[0] = 0;
}
char c, f;
inline void GET(int &n) {
    n = 0; f = 1;
    do {c = getchar(); if(c == '-') f = -1;} while(c > '9' || c < '0');
    while(c >= '0' && c <= '9') {n=n*10+c-'0';c=getchar();}
    n *= f;
}
int op[MAXN], tp;   //用栈来保存炸过的城市
bool dsd[MAXN];     //表示是否被炸过
int main() {
    GET(n); GET(m);
    char s[3]; int x;
    Ins(rt, 0); Ins(rt, n+1);
    while(m --) {
        scanf("%s", s);
        if(s[0] == 'D') GET(op[++ tp]), Ins(rt, op[tp]), dsd[op[tp]] = 1;
        else if(s[0] == 'Q') {
            GET(x); if(dsd[x]) puts("0");
            else printf("%d\n", t[Nxt(x,1)].v-t[Nxt(x,0)].v-1);
        }
        else dsd[op[tp]] = 0, Del(op[tp --]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值