一类 O(1) 单点插入求前驱后继的方法

考虑每 64 位多层分块,这样就可以用 64 位无符号整型以及内建函数快速查询。以下是分三层做到最大范围 \(64^3=262144\) 的实现,更大的实现是类似的。

代码中 opt 和 b1 是方便撤销用的。


#define ull uint64_t
#define ctz __builtin_ctzll
#define clz __builtin_clzll
const ull ma=((ull)-1)^63;
bool opt;
vector<pair<ull*,ull>> b1; 
vector<int> b2;
struct DS {
    ull a,b[64],c[64][64];
    int pre(ull x,int y) {
        if(y==64) return x?__lg(x):-1;
        x&=(1llu<<y)-1;
        if(x) return __lg(x);
        return -1;
    }
    int nxt(ull x,int y) {
        if(y==-1) return x?ctz(x):-1;
        if(y==63) return -1;
        x&=~((1llu<<y+1)-1);
        if(x) return ctz(x);
        return -1;
    }
    void clear() {
        a=0;
        memset(b,0,sizeof b);
        memset(c,0,sizeof c);
    }
    void ins(int x) {
        int o1=x>>6&63;
        int o2=x>>12&63;
        x&=63;
        if(opt) {
            b1.emplace_back(&c[o2][o1],c[o2][o1]);
            b1.emplace_back(&b[o2],b[o2]);
            b1.emplace_back(&a,a);
        }
        c[o2][o1]|=1llu<<x;
        b[o2]|=1llu<<o1;
        a|=1llu<<o2;
    }
    int pre(int x) {
        int o1=x>>6&63;
        int o2=x>>12&63;
        x&=63;
        int v=pre(c[o2][o1],x);
        if(v!=-1) return o2*64*64+o1*64+v;
        v=pre(b[o2],o1);
        if(v!=-1) {
            o1=v;
            return o2*64*64+o1*64+pre(c[o2][o1],64);
        }
        v=pre(a,o2);
        if(v!=-1) {
            o2=v;
            o1=pre(b[o2],64);
            return o2*64*64+o1*64+pre(c[o2][o1],64);
        }
        return -1;
    }
    int nxt(int x) {
        int o1=x>>6&63;
        int o2=x>>12&63;
        x&=63;
        int v=nxt(c[o2][o1],x);
        if(v!=-1) return o2*64*64+o1*64+v;
        v=nxt(b[o2],o1);
        if(v!=-1) {
            o1=v;
            return o2*64*64+o1*64+nxt(c[o2][o1],-1);
        }
        v=nxt(a,o2);
        if(v!=-1) {
            o2=v;
            o1=nxt(b[o2],-1);
            return o2*64*64+o1*64+nxt(c[o2][o1],-1);
        }
        return -1;
    }
}S;
posted @ 2026-11-20 19:16  dengchengyu  阅读(17)  评论(0)    收藏  举报