-
Notifications
You must be signed in to change notification settings - Fork 1
/
full_veb.hpp
100 lines (100 loc) · 2 KB
/
full_veb.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <algorithm>
#include <type_traits>
namespace Full_Veb_Implementation {
template<int s,class small_enough=void>
class vEB {
vEB<s/2> *tp;
vEB<(s+1)/2> *bt;
public:
int mi,mx;
vEB() {
mi=mx=-1;
tp=new vEB<s/2>;
bt=new vEB<(s+1)/2>[1<<(s/2)];
}
inline int suc(int x) const {
// assert(x>=0&&x<(1<<s));
if(x<mi) return mi;
if(mi==-1) return -1;
int c=x>>((s+1)/2),i=x&((1<<((s+1)/2))-1);
if(i<bt[c].mx) {
int w=bt[c].suc(i);
if(w==-1) return -1;
return (c<<((s+1)/2))|w;
}
int u=tp->suc(c);
if(u==-1) return -1;
return (u<<((s+1)/2))|bt[u].mi;
}
inline bool ins(int x) {
// assert(x>=0&&x<(1<<s));
if(mi==-1) {
mi=mx=x; return 1;
}
if(x==mi||x==mx) return 0;
if(x<mi) std::swap(mi,x);
if(x>mx) mx=x;
int c=x>>((s+1)/2),i=x&((1<<((s+1)/2))-1);
if(bt[c].mi==-1) tp->ins(c);
return bt[c].ins(i);
}
inline bool del(int x) {
if(mi==-1||x<mi) return 0;
// assert(x>=0&&x<(1<<s));
if(x==mi) {
int c=tp->mi;
if(c==-1) {
mi=mx=-1; return 1;
}
// assert(bt[c].mi!=-1);
x=mi=(c<<((s+1)/2))|bt[c].mi;
}
// assert(x>=0&&x<(1<<s));
int c=x>>((s+1)/2),i=x&((1<<((s+1)/2))-1);
if(bt[c].mi==-1) return 0;
if(!bt[c].del(i)) {
assert(bt[c].mi!=-1);
return 0;
}
if(bt[c].mi==-1) tp->del(c);
if(tp->mi==-1) mx=mi;
else {
int u=tp->mx;
mx=(u<<((s+1)/2))|bt[u].mx;
}
return 1;
}
};
template<bool cond,typename U>
using resolvedType=typename std::enable_if<cond,U>::type;
template<int s>
class vEB<s,resolvedType<(s<=5),void>> {
public:
unsigned u; int mi,mx;
vEB():u(0),mi(-1),mx(-1) {
}
inline int suc(int x) const {
if(x>=mx) return -1;
return x+1+__builtin_ctz(u>>(x+1));
}
inline bool ins(int x) {
if(u&(1u<<x)) return 0;
u^=1u<<x;
if(mi==-1||mi>x) mi=x;
if(x>mx) mx=x;
return 1;
}
inline bool del(int x) {
if(!(u&(1u<<x))) return 0;
u^=1u<<x;
if(!u) mi=mx=-1;
else {
mi=__builtin_ctz(u);
mx=31-__builtin_clz(u);
}
return 1;
}
};
}
template<int s>
using fullVeb=Full_Veb_Implementation::vEB<s>;