├── CPP ├── dynamic_wavelet_tree.cpp ├── euler_tour.cpp ├── fast_treap.cpp ├── fenwick_tree.cpp ├── fraction.cpp ├── link_cut_tree.cpp ├── red_black_tree.cpp ├── segment_tree_2d.cpp ├── segment_tree_beats.cpp ├── sparse_table.cpp ├── splay_tree.cpp ├── string_hash.cpp ├── suffix_array.cpp ├── suffix_automaton.cpp ├── suffix_tree.cpp └── wavelet_matrix.cpp ├── Clojure └── treap.clj ├── Go └── treap.go ├── Kotlin └── Treap.kt ├── Python └── Treap.py ├── README.md └── Rust ├── Treap.rs ├── UnionFind.rs └── splay.rs /CPP/dynamic_wavelet_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node { 5 | int x, y, s; 6 | node *p = 0; 7 | node *l = 0; 8 | node *r = 0; 9 | 10 | node(int v) { 11 | x = v; 12 | y = v; 13 | s = 1; 14 | } 15 | 16 | void upd() { 17 | s = 1; 18 | y = x; 19 | if(l) { 20 | y += l->y; 21 | s += l->s; 22 | } 23 | 24 | if(r) { 25 | y += r->y; 26 | s += r->s; 27 | } 28 | } 29 | 30 | int left_size() { 31 | return l ? l->s : 0; 32 | } 33 | }; 34 | 35 | struct splay_tree { 36 | node *root = 0; 37 | 38 | void rot(node *c) { 39 | auto p = c->p; 40 | auto g = p->p; 41 | 42 | if(g) 43 | (g->l == p ? g->l : g->r) = c; 44 | 45 | if(p->l == c) { 46 | p->l = c->r; 47 | c->r = p; 48 | if(p->l) p->l->p = p; 49 | } else { 50 | p->r = c->l; 51 | c->l = p; 52 | if(p->r) p->r->p = p; 53 | } 54 | 55 | p->p = c; 56 | c->p = g; 57 | 58 | p->upd(); 59 | c->upd(); 60 | } 61 | 62 | void splay(node *c) { 63 | while(c->p) { 64 | auto p = c->p; 65 | auto g = p->p; 66 | 67 | if(g) rot((g->l == p) == (p->l == c) ? p : c); 68 | rot(c); 69 | } 70 | c->upd(); 71 | root = c; 72 | } 73 | 74 | node* join(node *l, node *r) { 75 | if(not l) return r; 76 | if(not r) return l; 77 | 78 | while(l->r) l = l->r; 79 | 80 | splay(l); 81 | r->p = l; 82 | l->r = r; 83 | l->upd(); 84 | 85 | return l; 86 | } 87 | 88 | pair split(node *p, int idx) { 89 | if(not p) 90 | return make_pair(nullptr, nullptr); 91 | 92 | if(idx < 0) 93 | return make_pair(nullptr, p); 94 | 95 | if(idx >= p->s) 96 | return make_pair(p, nullptr); 97 | 98 | for(int lf = p->left_size(); idx != lf; lf = p->left_size()) { 99 | if(idx < lf) 100 | p = p->l; 101 | else 102 | p = p->r, idx -= lf+1; 103 | } 104 | 105 | splay(p); 106 | 107 | node *l = p; 108 | node *r = p->r; 109 | if(r) { 110 | l->r = r->p = 0; 111 | l->upd(); 112 | } 113 | return make_pair(l, r); 114 | } 115 | 116 | node* get(int idx) { 117 | auto p = root; 118 | for(int lf = p->left_size(); idx != lf; lf = p->left_size()) { 119 | if(idx < lf) 120 | p = p->l; 121 | else 122 | p = p->r, idx -= lf+1; 123 | } 124 | 125 | splay(p); 126 | 127 | return p; 128 | } 129 | 130 | int insert(int idx, int x) { 131 | node *l, *r; 132 | tie(l, r) = split(root, idx-1); 133 | int v = l ? l->y : 0; 134 | root = join(l, join(new node(x), r)); 135 | return v; 136 | } 137 | 138 | void erase(int idx) { 139 | node *l, *r; 140 | tie(l, r) = split(root, idx); 141 | root = join(l->l, r); 142 | delete l; 143 | } 144 | 145 | void append(int x) { 146 | root = join(root, new node(x)); 147 | } 148 | 149 | int rank(int idx) { 150 | node *l, *r; 151 | tie(l, r) = split(root, idx); 152 | int x = (l && l->l ? l->l->y : 0); 153 | root = join(l, r); 154 | return x; 155 | } 156 | 157 | int operator[](int idx) { 158 | return rank(idx); 159 | } 160 | 161 | ~splay_tree() { 162 | if(!root) 163 | return; 164 | 165 | vector nodes {root}; 166 | while(nodes.size()) { 167 | auto u = nodes.back(); 168 | nodes.pop_back(); 169 | if(u->l) nodes.emplace_back(u->l); 170 | if(u->r) nodes.emplace_back(u->r); 171 | delete u; 172 | } 173 | } 174 | }; 175 | 176 | struct wavelet { 177 | int A, Z; 178 | wavelet *l = 0; 179 | wavelet *r = 0; 180 | splay_tree b; 181 | 182 | wavelet(int L, int R) { 183 | A = L; 184 | Z = R; 185 | b.insert(0, 0); 186 | } 187 | 188 | ~wavelet() { 189 | delete l; 190 | delete r; 191 | } 192 | 193 | void append(int x) { 194 | if(A >= Z) 195 | return; 196 | 197 | int M = (A + Z) / 2; 198 | 199 | if(x <= M) { 200 | b.append(1); 201 | l = l ?: new wavelet(A, M); 202 | l->append(x); 203 | } else { 204 | b.append(0); 205 | r = r ?: new wavelet(M+1, Z); 206 | r->append(x); 207 | } 208 | } 209 | 210 | void insert(int idx, int x) { 211 | if(A >= Z) 212 | return; 213 | 214 | int M = (A + Z) / 2; 215 | 216 | if(x <= M) { 217 | l = l ?: new wavelet(A, M); 218 | l->insert(b.insert(idx, 1), x); 219 | } else { 220 | r = r ?: new wavelet(M+1, Z); 221 | r->insert(idx - b.insert(idx, 0), x); 222 | } 223 | } 224 | 225 | void erase(int idx) { 226 | if(A == Z) 227 | return; 228 | 229 | auto p = b.get(idx); 230 | int lf = p->l ? p->l->y : 0; 231 | int x = p->x; 232 | b.erase(idx); 233 | if(x == 1) 234 | l->erase(lf); 235 | else 236 | r->erase(idx-lf); 237 | } 238 | 239 | int kth(int L, int R, int k) { 240 | if(A == Z) 241 | return A; 242 | 243 | int x = b.rank(L); 244 | int y = b.rank(R); 245 | 246 | if(k <= y-x) 247 | return l->kth(x, y, k); 248 | else 249 | return r->kth(L-x, R-y, k-(y-x)); 250 | } 251 | }; 252 | 253 | int main() { 254 | cin.tie(0); 255 | cin.sync_with_stdio(0); 256 | 257 | wavelet t(0, 1e9); 258 | 259 | int n = 100000; 260 | for(int i = 0; i < n; ++i) 261 | t.insert(i, i+1); 262 | t.erase(0);n--; 263 | cout << t.kth(0, n, 15689); 264 | } 265 | -------------------------------------------------------------------------------- /CPP/euler_tour.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | using ll = long long; 5 | 6 | int const N = 100 * 1000 + 16; 7 | int const M = 1000 * 1000 * 1000 + 7; 8 | 9 | int n; 10 | vector g[N]; 11 | vector dist, tin, tour; 12 | vector> st; 13 | 14 | int dfs(int u, int p) { 15 | dist[u] = dist[p] + 1; 16 | 17 | tin[u] = tour.size(); 18 | tour.emplace_back(u); 19 | 20 | for(int v : g[u]) { 21 | if(v == p) 22 | continue; 23 | dfs(v, u); 24 | tour.emplace_back(u); 25 | } 26 | } 27 | 28 | void build() { 29 | int n = tour.size(); 30 | int logn = 32 - __builtin_clz(n); 31 | 32 | st.assign(logn, vector(n)); 33 | 34 | copy(tour.begin(), tour.end(), st[0].begin()); 35 | 36 | for(int j = 1; (1< r) 52 | swap(l, r); 53 | 54 | int b = 31 - __builtin_clz(r-l+1); 55 | int x = st[b][l]; 56 | int y = st[b][r-(1<> n; 69 | for(int i = 1; i < n; ++i) { 70 | int u, v; 71 | cin >> u >> v; 72 | g[u].emplace_back(v); 73 | g[v].emplace_back(u); 74 | } 75 | 76 | tin.resize(n+1); 77 | dist.resize(n+1); 78 | 79 | tour.reserve(2*n-1); 80 | 81 | dfs(1, 0); 82 | build(); 83 | 84 | 85 | } 86 | -------------------------------------------------------------------------------- /CPP/fast_treap.cpp: -------------------------------------------------------------------------------- 1 | template > 2 | struct treap { 3 | template 4 | struct tnode { 5 | R x; 6 | int y, s; 7 | tnode *l, *r; 8 | tnode(R const &v, int rnd) { 9 | x = v; 10 | y = rnd; 11 | s = 1; 12 | l = r = 0; 13 | } 14 | ~tnode() { 15 | delete l; 16 | delete r; 17 | } 18 | inline tnode *upd() { 19 | s = 1; 20 | if (l) s += l->s; 21 | if (r) s += r->s; 22 | return this; 23 | } 24 | }; 25 | 26 | using node = tnode; 27 | F f; 28 | node *root; 29 | mt19937 rand; 30 | 31 | treap() { 32 | root = 0; 33 | rand.seed(chrono::steady_clock::now().time_since_epoch().count()); 34 | } 35 | 36 | ~treap() { delete root; } 37 | 38 | node *join(node *l, node *r) { 39 | if (not l) return r; 40 | if (not r) return l; 41 | if (l->y > r->y) { 42 | l->r = join(l->r, r); 43 | return l->upd(); 44 | } else { 45 | r->l = join(l, r->l); 46 | return r->upd(); 47 | } 48 | } 49 | 50 | node *insert(node *p, node *x) { 51 | if (not p) return x; 52 | if (f(x->x, p->x)) { 53 | p->l = insert(p->l, x); 54 | auto c = p->l; 55 | if (c->y > p->y) { 56 | p->l = c->r; 57 | c->r = p->upd(); 58 | p = c; 59 | } 60 | } else { 61 | p->r = insert(p->r, x); 62 | auto c = p->r; 63 | if (c->y > p->y) { 64 | p->r = c->l; 65 | c->l = p->upd(); 66 | p = c; 67 | } 68 | } 69 | return p->upd(); 70 | } 71 | 72 | node *erase(node *p, T const &x) { 73 | if (not p) return 0; 74 | if (f(x, p->x)) { 75 | p->l = erase(p->l, x); 76 | p->upd(); 77 | } else if (f(p->x, x)) { 78 | p->r = erase(p->r, x); 79 | p->upd(); 80 | } else { 81 | auto kids = join(p->l, p->r); 82 | p->l = p->r = 0; 83 | delete p; 84 | p = kids; 85 | } 86 | return p; 87 | } 88 | 89 | void insert(T const &x) { root = insert(root, new node(x, rand())); } 90 | void erase(T const &x) { root = erase(root, x); } 91 | 92 | int print(node *p) { 93 | if (not p) return 0; 94 | auto l = print(p->l); 95 | cout << p->x << '\n'; 96 | auto r = print(p->r); 97 | return max(l, r) + 1; 98 | } 99 | 100 | int print() { return print(root); } 101 | }; 102 | -------------------------------------------------------------------------------- /CPP/fenwick_tree.cpp: -------------------------------------------------------------------------------- 1 | template 2 | struct fenwick { 3 | int n; 4 | vector a, b; 5 | 6 | fenwick(int s) { 7 | n = s; 8 | a.assign(n+1, 0); 9 | b.assign(n+1, 0); 10 | } 11 | 12 | void update(vector& bit, int idx, T v) { 13 | for(int i = idx; i <= n; i += (i&-i)) 14 | bit[i] += v; 15 | } 16 | 17 | void update(int l, int r, T v) { 18 | update(a, l, v); 19 | update(a, r+1, -v); 20 | update(b, l, -v*(l-1)); 21 | update(b, r+1, v*r); 22 | } 23 | 24 | T query(vector const& bit, T idx) { 25 | T sum = 0; 26 | for(int i = idx; i > 0; i -= (i&-i)) 27 | sum += bit[i]; 28 | return sum; 29 | } 30 | 31 | T query(int idx) { 32 | return query(a, idx) * idx + query(b, idx); 33 | } 34 | 35 | T query(int l, int r) { 36 | return query(r) - query(l-1); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /CPP/fraction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | using ll = long long; 5 | 6 | struct fraction { 7 | using T = ll; 8 | 9 | T x = 0, y = 1; 10 | 11 | fraction() { 12 | x = 0; 13 | y = 1; 14 | } 15 | 16 | fraction(T a) { 17 | x = a; 18 | y = 1; 19 | } 20 | 21 | fraction(T a, T b) { 22 | x = a; 23 | y = b; 24 | reduce(); 25 | } 26 | 27 | void reduce() { 28 | auto g = __gcd(abs(x), abs(y)); 29 | x /= g; 30 | y /= g; 31 | 32 | if(y < 0) 33 | x = -x, y = -y; 34 | } 35 | 36 | T lcm(T x, T y) const { 37 | return x / __gcd(x, y) * y; 38 | } 39 | 40 | fraction flip() const { 41 | if(x == 0) 42 | return *this; 43 | return fraction{y, x}; 44 | } 45 | 46 | operator T() { 47 | return x/y; 48 | } 49 | 50 | fraction& operator=(T a) { 51 | x = a; 52 | y = 1; 53 | return *this; 54 | } 55 | 56 | fraction operator-() const { 57 | return fraction(-x, y); 58 | } 59 | 60 | fraction operator+(fraction const& b) const { 61 | auto m = lcm(y, b.y); 62 | 63 | T x2 = (m/y)*x + (m/b.y)*b.x; 64 | T y2 = m; 65 | 66 | return fraction(x2, y2); 67 | } 68 | 69 | fraction operator-(fraction const& b) const { 70 | auto f = -b; 71 | return *this+f; 72 | } 73 | 74 | fraction operator*(fraction const& b) const { 75 | return fraction(x*b.x, y*b.y); 76 | } 77 | 78 | fraction operator/(fraction const& b) const { 79 | return *this * b.flip(); 80 | } 81 | 82 | bool operator==(fraction const& b) const { 83 | return (x==b.x && y==b.y); 84 | } 85 | 86 | bool operator!=(fraction const& b) const { 87 | return not (*this == b); 88 | } 89 | 90 | bool operator<(fraction const& b) const { 91 | return x*b.y < y*b.x; 92 | } 93 | 94 | bool operator>(fraction const& b) const { 95 | return x*b.y > y*b.x; 96 | } 97 | 98 | bool operator<=(fraction const& b) const { 99 | return x*b.y <= y*b.x; 100 | } 101 | 102 | bool operator>=(fraction const& b) const { 103 | return x*b.y >= y*b.x; 104 | } 105 | 106 | friend istream& operator>>(istream& in, fraction& me) { 107 | return in >> me.x; 108 | } 109 | 110 | friend ostream& operator<<(ostream& out, fraction& me) { 111 | return out << me.x << "/" << me.y; 112 | } 113 | }; 114 | 115 | int main() { 116 | fraction a = 2; 117 | fraction b = 6; 118 | fraction c = a/b; 119 | 120 | cout << c << endl; 121 | } 122 | -------------------------------------------------------------------------------- /CPP/link_cut_tree.cpp: -------------------------------------------------------------------------------- 1 | struct node { 2 | int x; 3 | node *l = 0; 4 | node *r = 0; 5 | node *p = 0; 6 | bool rev = false; 7 | 8 | node() = default; 9 | 10 | node(int v) { 11 | x = v; 12 | } 13 | 14 | void push() { 15 | if(rev) { 16 | rev = false; 17 | swap(l, r); 18 | if(l) l->rev ^= true; 19 | if(r) r->rev ^= true; 20 | } 21 | } 22 | 23 | bool is_root() { 24 | return p == 0 || (p->l != this && this != p->r); 25 | } 26 | }; 27 | 28 | struct lct { 29 | vector a; 30 | 31 | lct(int n) { 32 | a.resize(n+1); 33 | for(int i = 1; i <= n; ++i) 34 | a[i].x = i; 35 | } 36 | 37 | void rot(node* c) { 38 | auto p = c->p; 39 | auto g = p->p; 40 | 41 | if(!p->is_root()) 42 | (g->r == p ? g->r : g->l) = c; 43 | 44 | p->push(); 45 | c->push(); 46 | 47 | if(p->l == c) { // rtr 48 | p->l = c->r; 49 | c->r = p; 50 | if(p->l) p->l->p = p; 51 | } else { // rtl 52 | p->r = c->l; 53 | c->l = p; 54 | if(p->r) p->r->p = p; 55 | } 56 | 57 | p->p = c; 58 | c->p = g; 59 | } 60 | 61 | void splay(node* c) { 62 | while(!c->is_root()) { 63 | auto p = c->p; 64 | auto g = p->p; 65 | if(!p->is_root()) 66 | rot((g->r == p) == (p->r == c) ? p : c); 67 | rot(c); 68 | } 69 | c->push(); 70 | } 71 | 72 | node* access(int v) { 73 | node* last = 0; 74 | node* c = &a[v]; 75 | for(node* p = c; p; p = p->p) { 76 | splay(p); 77 | p->r = last; 78 | last = p; 79 | } 80 | splay(c); 81 | return last; 82 | } 83 | 84 | void make_root(int v) { 85 | access(v); 86 | auto* c = &a[v]; 87 | if(c->l) 88 | c->l->rev ^= true, c->l = 0; 89 | } 90 | 91 | void link(int u, int v) { 92 | make_root(v); 93 | node* c = &a[v]; 94 | c->p = &a[u]; 95 | } 96 | 97 | void cut(int u, int v) { 98 | make_root(u); 99 | access(v); 100 | if(a[v].l) { 101 | a[v].l->p = 0; 102 | a[v].l = 0; 103 | } 104 | } 105 | 106 | bool connected(int u, int v) { 107 | access(u); 108 | access(v); 109 | return a[u].p; 110 | } 111 | }; 112 | -------------------------------------------------------------------------------- /CPP/red_black_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | using ll = long long; 4 | 5 | template < class T > struct node { 6 | T x; 7 | unsigned int s = color_mask | 1; 8 | 9 | node *k[2] = { }; 10 | 11 | node(T v) { 12 | x = v; 13 | } 14 | 15 | ~node() { 16 | delete k[0]; 17 | delete k[1]; 18 | } 19 | 20 | static unsigned int const color_mask = ~INT_MAX; 21 | static unsigned int const size_mask = INT_MAX; 22 | 23 | static inline int size(node * p) { 24 | return p ? (p->s & size_mask) : 0; 25 | } 26 | 27 | static inline bool is_red(node * p) { 28 | return p ? (p->s & color_mask) : 0; 29 | } 30 | 31 | // 1 red, 0 black 32 | static inline void set(node * p, unsigned int c) { 33 | p->s = (c << 31) | (p->s & size_mask); 34 | } 35 | 36 | static inline void flip(node * p) { 37 | p->s |= color_mask; 38 | p->k[0]->s &= size_mask; 39 | p->k[1]->s &= size_mask; 40 | } 41 | 42 | static inline void swap_colors(node * l, node * r) { 43 | auto lc = l->s & color_mask; 44 | auto rc = r->s & color_mask; 45 | l->s = rc | (l->s & size_mask); 46 | r->s = lc | (r->s & size_mask); 47 | } 48 | 49 | // 0 left, 1 right 50 | node *rot(int d) { 51 | int o = d ^ 1; 52 | auto c = k[o]; 53 | k[o] = c->k[d]; 54 | c->k[d] = upd(); 55 | swap_colors(c, this); 56 | return c->upd(); 57 | } 58 | 59 | node *upd() { 60 | s = (s & color_mask) + size(k[0]) + 1 + size(k[1]); 61 | return this; 62 | } 63 | }; 64 | 65 | template < class T > struct rbt { 66 | using tnode = node < T >; 67 | tnode *root = 0; 68 | 69 | ~rbt() { 70 | delete root; 71 | } 72 | 73 | tnode *insert(tnode * p, T const &x) { 74 | if (not p) 75 | return new tnode(x); 76 | int d = (x >= p->x); 77 | p->k[d] = insert(p->k[d], x); 78 | return fix(p, d); 79 | } 80 | 81 | void insert(T x) { 82 | root = insert(root, x); 83 | } 84 | 85 | int b; 86 | tnode *erase(tnode * p, T const &x, tnode * fam) { 87 | if (not p) 88 | return 0; 89 | 90 | int d = (!fam and x >= p->x); 91 | int o = d ^ 1; 92 | auto kid = p->k[d]; 93 | 94 | // lost & found? 95 | if (not kid && (fam || p->x == x)) { 96 | if (fam) 97 | swap(fam->x, p->x); 98 | 99 | // other kid? 100 | if (p->k[o]) { 101 | auto ret = p->k[o]; 102 | p->k[o] = 0; 103 | delete p; 104 | 105 | tnode::set(ret, 0); 106 | return ret; 107 | } else { 108 | // argh black leaf baby! 109 | b = !tnode::is_red(p); 110 | delete p; 111 | return 0; 112 | } 113 | } 114 | 115 | if (p->x == x) 116 | fam = p; 117 | 118 | p->k[d] = erase(p->k[d], x, fam); 119 | 120 | return fix_erase(p, d); 121 | } 122 | 123 | void erase(T x) { 124 | b = 0; 125 | root = erase(root, x, 0); 126 | b = 0; 127 | } 128 | 129 | tnode *fix_erase(tnode * p, int d) { 130 | auto kid = p->k[d]; 131 | int o = d ^ 1; 132 | 133 | if (b) { 134 | // am I red? 135 | if (tnode::is_red(kid)) { 136 | // done yaaay 137 | b = 0; 138 | tnode::set(kid, 0); 139 | p->upd(); 140 | } else if (tnode::is_red(p->k[o])) { 141 | // is sibling red? 142 | // rotate towards me 143 | p = p->rot(d); 144 | p->k[d] = fix_erase(p->k[d], d); 145 | p = fix_erase(p, d); 146 | } else { 147 | // blacky 148 | // is close nephew red? 149 | if (tnode::is_red(p->k[o]->k[d])) { 150 | // go away!!! 151 | p->k[o] = p->k[o]->rot(o); 152 | } 153 | // is far nephew red? 154 | if (tnode::is_red(p->k[o]->k[o])) { 155 | // we are done! 156 | b = 0; 157 | p = p->rot(d); 158 | tnode::set(p->k[o], 0); 159 | } else { 160 | // both nephews are black! make bro red to even sides 161 | tnode::set(p->k[o], 1); 162 | p->upd(); 163 | } 164 | } 165 | return p; 166 | } else { 167 | return fix(p, d); 168 | } 169 | } 170 | 171 | tnode *fix(tnode * p, int d) { 172 | auto kid = p->k[d]; 173 | int o = d ^ 1; 174 | // is a red suspect? 175 | if (tnode::is_red(kid)) { 176 | if (tnode::is_red(p->k[o])) { 177 | // if sibling is red just flip 178 | tnode::flip(p); 179 | } else if (tnode::is_red(kid->k[d])) { 180 | // single rotation 181 | p = p->rot(o); 182 | } else if (tnode::is_red(kid->k[o])) { 183 | // double rotation 184 | p->k[d] = kid->rot(d); 185 | p = p->rot(o); 186 | } 187 | } 188 | return p->upd(); 189 | } 190 | 191 | int print(tnode * p) { 192 | if (not p) 193 | return 0; 194 | auto l = print(p->k[0]); 195 | // cout << p->x << '\n'; 196 | auto r = print(p->k[1]); 197 | // black height 198 | assert(l == r); 199 | // double red 200 | assert(not(tnode::is_red(p) 201 | && (tnode::is_red(p->k[0]) || tnode::is_red(p->k[1])))); 202 | // subtree size 203 | assert(tnode::size(p) == tnode::size(p->k[0]) + 1 + tnode::size(p->k[1])); 204 | return not(tnode::is_red(p)) + max(l, r); 205 | } 206 | 207 | int print() { 208 | return print(root); 209 | } 210 | }; 211 | 212 | int main() 213 | { 214 | cin.tie(0); 215 | cin.sync_with_stdio(0); 216 | 217 | rbt < int >t; 218 | int n = 100 * 1000; 219 | 220 | for (int i = 0; i < n; ++i) { 221 | t.insert(i); 222 | } 223 | 224 | for (int i = 0; i < n / 2; ++i) { 225 | auto v = rand() % n; 226 | t.erase(v); 227 | } 228 | 229 | int h = t.print(); 230 | 231 | cout << h << endl; 232 | } 233 | -------------------------------------------------------------------------------- /CPP/segment_tree_2d.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct segment { 5 | int n; 6 | vector t; 7 | 8 | segment(int s) { 9 | n = s; 10 | t.assign(n+n, 0); 11 | } 12 | 13 | void update(int l, int r, int v) { 14 | for(l += n, r += n; l <= r; l >>= 1, r >>= 1) { 15 | if(l&1) t[l++] ^= v; 16 | if((r&1)^1) t[r--] ^= v; 17 | } 18 | } 19 | 20 | int query(int i) { 21 | int sum = 0; 22 | for(i += n; i > 0; i >>= 1) 23 | sum ^= t[i]; 24 | return sum; 25 | } 26 | }; 27 | 28 | struct segment2D { 29 | int n, m; 30 | vector t; 31 | 32 | segment2D(int x, int y) { 33 | n = x; 34 | m = y; 35 | t.assign(n+n, segment(m)); 36 | } 37 | 38 | void add(int x1, int y1, int x2, int y2, int v) { 39 | for(x1 += n, x2 += n; x1 <= x2; x1 >>= 1, x2 >>= 1) { 40 | if(x1&1) t[x1++].update(y1, y2, v); 41 | if((x2&1)^1) t[x2--].update(y1, y2, v); 42 | } 43 | } 44 | 45 | void rem(int x1, int y1, int x2, int y2, int v) { 46 | add(x1, y1, x2, y2, v); 47 | } 48 | 49 | int query(int x, int y) { 50 | int sum = 0; 51 | for(x += n; x > 0; x >>= 1) 52 | sum ^= t[x].query(y); 53 | return sum; 54 | } 55 | }; 56 | 57 | int n, m, q; 58 | 59 | int main() { 60 | cin.tie(0); 61 | cin.sync_with_stdio(0); 62 | 63 | cin >> n >> m >> q; 64 | segment2D a(n, m), a_xor(n, m); 65 | 66 | random_device rd; 67 | mt19937 rand(rd()); 68 | set> s; 69 | 70 | int mn = 0; 71 | while(q--) { 72 | int t, x1, y1, x2, y2; 73 | cin >> t >> x1 >> y1 >> x2 >> y2; 74 | --x1;--y1;--x2;--y2; 75 | 76 | if(t == 1) { 77 | auto f = s.lower_bound(make_tuple(x1, y1, x2, y2, mn, mn)); 78 | if(f != s.end()) { 79 | int a1, b1, a2, b2; 80 | tie(a1, b1, a2, b2, ignore, ignore) = *f; 81 | if(tie(a1, b1, a2, b2) == tie(x1, y1, x2, y2)) 82 | continue; 83 | } 84 | 85 | 86 | int p1 = q+1000000, p2 = rand(); 87 | mn = min(mn, p2); 88 | s.insert(make_tuple(x1, y1, x2, y2, p1, p2)); 89 | 90 | a.add(x1, y1, x2, y2, p1); 91 | a_xor.add(x1, y1, x2, y2, p2); 92 | } else if(t == 2) { 93 | auto f = s.lower_bound(make_tuple(x1, y1, x2, y2, mn, mn)); 94 | int p1, p2; 95 | tie(ignore, ignore, ignore, ignore, p1, p2) = *f; 96 | s.erase(f); 97 | 98 | a.rem(x1, y1, x2, y2, p1); 99 | a_xor.rem(x1, y1, x2, y2, p2); 100 | } else { 101 | bool can = true; 102 | can &= 0 <= x1 && 0 <= y1 && 0 <= x2 && 0 <= y2; 103 | can &= x1 < n && y1 < m && x2 < n && y2 < m; 104 | can &= a.query(x1, y1) == a.query(x2, y2); 105 | can &= a_xor.query(x1, y1) == a_xor.query(x2, y2); 106 | cout << (can ? "Yes\n" : "No\n"); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /CPP/segment_tree_beats.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | using ll = long long; 5 | 6 | int const N = 1 << 21; 7 | 8 | ll sum[N]; 9 | int mx1[N]; 10 | int mx2[N]; 11 | int cnt[N]; 12 | 13 | struct segment_tree 14 | { 15 | int n; 16 | int ql, qr; 17 | 18 | segment_tree(vector < int >const &a) 19 | { 20 | n = a.size(); 21 | build(1, 1, n, a); 22 | } 23 | 24 | inline void calc(int i) 25 | { 26 | int lf = 2 * i; 27 | int rg = lf + 1; 28 | 29 | cnt[i] = 0; 30 | sum[i] = sum[lf] + sum[rg]; 31 | mx1[i] = max(mx1[lf], mx1[rg]); 32 | mx2[i] = max(mx2[lf], mx2[rg]); 33 | 34 | if (mx1[i] == mx1[lf]) 35 | cnt[i] += cnt[lf]; 36 | else 37 | mx2[i] = max(mx2[i], mx1[lf]); 38 | 39 | if (mx1[i] == mx1[rg]) 40 | cnt[i] += cnt[rg]; 41 | else 42 | mx2[i] = max(mx2[i], mx1[rg]); 43 | } 44 | 45 | void build(int i, int l, int r, vector < int >const &a) 46 | { 47 | if (l == r) 48 | { 49 | cnt[i] = 1; 50 | mx2[i] = -10; 51 | sum[i] = mx1[i] = a[l]; 52 | } 53 | else 54 | { 55 | int m = (l + r) / 2; 56 | build(2 * i, l, m, a); 57 | build(2 * i + 1, m + 1, r, a); 58 | calc(i); 59 | } 60 | } 61 | 62 | void push(int i, int l, int r) 63 | { 64 | if (l == r) 65 | return; 66 | 67 | int lf = 2 * i; 68 | int rg = lf + 1; 69 | 70 | if (mx1[lf] > mx1[i]) 71 | { 72 | sum[lf] -= (mx1[lf] - mx1[i]) * ll(cnt[lf]); 73 | mx1[lf] = mx1[i]; 74 | } 75 | 76 | if (mx1[rg] > mx1[i]) 77 | { 78 | sum[rg] -= (mx1[rg] - mx1[i]) * ll(cnt[rg]); 79 | mx1[rg] = mx1[i]; 80 | } 81 | } 82 | 83 | void update(int i, int l, int r, int x) 84 | { 85 | if (l > r) 86 | return; 87 | 88 | push(i, l, r); 89 | 90 | if (mx1[i] <= x) 91 | return; 92 | 93 | if (ql <= l && r <= qr && mx2[i] < x && x < mx1[i]) 94 | { 95 | sum[i] -= (mx1[i] - x) * ll(cnt[i]); 96 | mx1[i] = x; 97 | } 98 | else 99 | { 100 | if (l == r) 101 | return; 102 | int m = (l + r) / 2; 103 | if (ql <= m) 104 | update(2 * i, l, m, x); 105 | if (m < qr) 106 | update(2 * i + 1, m + 1, r, x); 107 | calc(i); 108 | } 109 | } 110 | 111 | void update(int l, int r, int x) 112 | { 113 | ql = l; 114 | qr = r; 115 | update(1, 1, n, x); 116 | } 117 | 118 | 119 | ll query_sum(int i, int l, int r) 120 | { 121 | push(i, l, r); 122 | 123 | if (ql <= l && r <= qr) 124 | { 125 | return sum[i]; 126 | } 127 | else 128 | { 129 | int m = (l + r) / 2; 130 | ll x = 0; 131 | if (ql <= m) 132 | x += query_sum(2 * i, l, m); 133 | if (m < qr) 134 | x += query_sum(2 * i + 1, m + 1, r); 135 | return x; 136 | } 137 | } 138 | 139 | ll query_sum(int l, int r) 140 | { 141 | ql = l; 142 | qr = r; 143 | return query_sum(1, 1, n); 144 | } 145 | 146 | 147 | int query_max(int i, int l, int r) 148 | { 149 | push(i, l, r); 150 | 151 | if (ql <= l && r <= qr) 152 | { 153 | return mx1[i]; 154 | } 155 | else 156 | { 157 | int m = (l + r) / 2; 158 | int x = 0; 159 | if (ql <= m) 160 | x = max(x, query_max(2 * i, l, m)); 161 | if (m < qr) 162 | x = max(x, query_max(2 * i + 1, m + 1, r)); 163 | return x; 164 | } 165 | } 166 | 167 | int query_max(int l, int r) 168 | { 169 | ql = l; 170 | qr = r; 171 | return query_max(1, 1, n); 172 | } 173 | }; 174 | -------------------------------------------------------------------------------- /CPP/sparse_table.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | template> 6 | struct sparse_table { 7 | int n; 8 | F comp; 9 | vector> st; 10 | 11 | sparse_table() = default; 12 | 13 | template 14 | sparse_table(iter l, iter r) { 15 | n = distance(l, r); 16 | int logn = 32 - __builtin_clz(n); 17 | st.assign(logn, vector(n)); 18 | 19 | // build 20 | auto it = l; 21 | for(int i = 0; i < n; ++i, ++it) 22 | st[0][i] = *it; 23 | 24 | for(int j = 1; (1< a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 45 | 46 | sparse_table t(a.begin(), a.end()); 47 | 48 | assert(t.query(0, 9) == 1); 49 | } 50 | -------------------------------------------------------------------------------- /CPP/splay_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | using ll = long long; 6 | 7 | template 8 | struct tnode { 9 | T x; 10 | tnode *p; 11 | tnode *l; 12 | tnode *r; 13 | 14 | tnode() { l = r = p = 0; } 15 | 16 | tnode(T v) : tnode() { x = v; } 17 | 18 | tnode *upd() { return this; } 19 | }; 20 | 21 | template > 22 | struct splay_tree { 23 | F f; 24 | using node = tnode; 25 | 26 | node *root; 27 | 28 | deque store; 29 | vector empty; 30 | 31 | node *new_node(T const &x) { 32 | if (empty.empty()) { 33 | store.emplace_back(x); 34 | return &store.back(); 35 | } else { 36 | auto v = empty.back(); 37 | empty.pop_back(); 38 | *v = node(x); 39 | return v; 40 | } 41 | } 42 | 43 | void delete_node(node *p) { empty.emplace_back(p); } 44 | 45 | splay_tree() { root = 0; } 46 | 47 | ~splay_tree() {} 48 | 49 | node *rot(node *c) { 50 | auto p = c->p; 51 | auto g = p->p; 52 | if (p->l == c) { // right 53 | p->l = c->r; 54 | if (p->l) p->l->p = p; 55 | c->r = p; 56 | } else { // left 57 | p->r = c->l; 58 | if (p->r) p->r->p = p; 59 | c->l = p; 60 | } 61 | if (g) { 62 | if (g->l == p) 63 | g->l = c; 64 | else 65 | g->r = c; 66 | } 67 | p->p = c; 68 | c->p = g; 69 | p->upd(); 70 | return c->upd(); 71 | } 72 | 73 | node *splay(node *c) { 74 | while (c->p) { 75 | auto p = c->p; 76 | auto g = p->p; 77 | if (g && (g->l == p) == (p->l == c)) rot(p); 78 | rot(c); 79 | } 80 | return c->upd(); 81 | } 82 | 83 | pair split(node *p, T const x) { 84 | node *l = 0; 85 | node *r = 0; 86 | node *last = 0; 87 | node *last_valid = 0; 88 | while (p) { 89 | last = p; 90 | if (f(x, p->x)) { // x < p->x 91 | p = p->l; 92 | } else { 93 | last_valid = p; 94 | p = p->r; 95 | } 96 | } 97 | if (last_valid) { 98 | splay(last_valid); 99 | l = last_valid; 100 | r = l->r; 101 | l->r = 0; 102 | l->upd(); 103 | if (r) r->p = 0; 104 | } else if (last) { 105 | r = splay(last); 106 | } 107 | return make_pair(l, r); 108 | } 109 | 110 | node *join(node *l, node *r) { 111 | if (!l || !r) return l ?: r; 112 | while (l->r) l = l->r; 113 | splay(l); 114 | l->r = r; 115 | r->p = l; 116 | return l->upd(); 117 | } 118 | 119 | void insert(T const &x) { 120 | auto [l, r] = split(root, x); 121 | root = join(l, join(new_node(x), r)); 122 | } 123 | 124 | void erase(T const &x) { 125 | auto [l, r] = split(root, x); 126 | if (l && l->x == x) { 127 | auto lf = l->l; 128 | auto rg = l->r; 129 | if (lf) lf->p = 0; 130 | if (rg) rg->p = 0; 131 | delete_node(l); 132 | l = join(lf, rg); 133 | } 134 | root = join(l, r); 135 | } 136 | 137 | void print() { 138 | if (root) { 139 | vector> stk; 140 | stk.emplace_back(root, false); 141 | while (stk.size()) { 142 | auto state = stk.back(); 143 | auto p = state.first; 144 | if (not state.second) { 145 | stk.back().second = true; 146 | if (p->l) stk.emplace_back(p->l, false); 147 | } else { 148 | cout << p->x << '\n'; 149 | stk.pop_back(); 150 | if (p->r) stk.emplace_back(p->r, false); 151 | } 152 | } 153 | } 154 | } 155 | }; 156 | 157 | int main() { 158 | cin.tie(0); 159 | cin.sync_with_stdio(0); 160 | 161 | int n; 162 | cin >> n; 163 | splay_tree t; 164 | for (int i = 0; i < n; ++i) { 165 | t.insert(i); 166 | } 167 | 168 | // t.print(); 169 | } 170 | -------------------------------------------------------------------------------- /CPP/string_hash.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | class string_hash { 6 | public: 7 | int n; 8 | vector f; 9 | vector h; 10 | 11 | constexpr static bool is_mersenne(ll x) { 12 | return not (x&(x+1)); 13 | } 14 | 15 | constexpr static bool is_power_of_two(ll x) { 16 | return not (x&(x-1)); 17 | } 18 | 19 | template 20 | inline static enable_if_t fix(ll x) { 21 | x = (x >> o) + (x & mod); 22 | x = (x >> o) + (x & mod); 23 | return x; 24 | } 25 | 26 | template 27 | inline static enable_if_t fix(ll x) { 28 | return x & (mod-1); 29 | } 30 | 31 | template 32 | inline static enable_if_t fix(ll x) { 33 | return x%mod; 34 | } 35 | 36 | template 37 | static int hash_of(iter l, iter r) { 38 | ll x = 0; 39 | for(iter it = l; it != r; ++it) 40 | x = fix(x*p + *it - 'a' + 1); 41 | return x; 42 | } 43 | 44 | template 45 | string_hash(iter l, iter r) { 46 | n = distance(l, r); 47 | assert(n >= 0); 48 | h.assign(n+1, 0); 49 | f.assign(n+1, 1); 50 | 51 | ll x = 1, y = 0; 52 | iter it = l; 53 | for(int i = 0; i < n; ++i, ++it) { 54 | f[i+1] = x = fix(x * p); 55 | h[i+1] = y = fix(y*p + (*it) - 'a' + 1); 56 | } 57 | } 58 | 59 | int query(int l, int r) { 60 | ll x = fix(h[r+1] - fix(1ll * h[l] * f[r-l+1])); 61 | return fix(x+mod); 62 | } 63 | }; 64 | 65 | int main() { 66 | string s = "hello"; 67 | int x = string_hash<31,257>::hash_of(s.begin(), s.end()); 68 | 69 | string_hash<31,257> hs(s.begin(), s.end()); 70 | int y = hs.query(0, 4); 71 | 72 | assert(x == y); 73 | } 74 | -------------------------------------------------------------------------------- /CPP/suffix_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | using ll = long long; 4 | 5 | vector suf_con(string const& s) { 6 | int n = s.size(); 7 | 8 | if(n == 0) return {}; 9 | 10 | vector cnt, sa(n), tmp(n), rank[2]; 11 | rank[0].resize(n); 12 | rank[1].resize(n); 13 | 14 | iota(sa.begin(), sa.end(), 0); 15 | for(int i = 0; i < n; ++i) 16 | rank[0][sa[i]] = s[sa[i]]; 17 | 18 | for(int len = 0; len < n; len = max(1, 2 * len)) { 19 | for(auto x : sa) 20 | rank[1][x] = (x + len < n) ? rank[0][x + len] : 0; 21 | 22 | int m = 1 + rank[0][sa.back()]; 23 | if(not len) 24 | m = 1 + *max_element(rank[0].begin(), rank[0].end()); 25 | 26 | for(int r = 1; r >= 0; --r) { 27 | swap(sa, tmp); 28 | cnt.assign(m, 0); 29 | for(auto x : tmp) 30 | ++cnt[rank[r][x]]; 31 | partial_sum(cnt.begin(), cnt.end(), cnt.begin()); 32 | for(int i = n - 1; i >= 0; --i) 33 | sa[--cnt[rank[r][tmp[i]]]] = tmp[i]; 34 | } 35 | 36 | for(int i = 0, j = 0, k = 1; i < n; i = j, ++k) { 37 | int r0 = rank[0][sa[i]]; 38 | int r1 = rank[1][sa[i]]; 39 | while(j < n && r0 == rank[0][sa[j]] && r1 == rank[1][sa[j]]) 40 | rank[0][sa[j++]] = k; 41 | } 42 | 43 | if(rank[0][sa.back()] == n) break; 44 | } 45 | return sa; 46 | } 47 | 48 | vector lcp_con(string const &w, vector const& sa, vector const& rev) { 49 | int n = w.size(); 50 | vector lcp(n); 51 | for(int i = 0, k = 0; i < n; ++i, k -= k>0) { 52 | int idx = rev[i]; 53 | if(idx == n-1) { 54 | k = 0; 55 | } else { 56 | while(sa[idx]+k < n && 57 | sa[idx+1]+k < n && 58 | w[sa[idx]+k] == w[sa[idx+1]+k]) 59 | k++; 60 | } 61 | lcp[idx] = k; 62 | } 63 | return lcp; 64 | } 65 | 66 | 67 | int main() 68 | { 69 | cin.tie(0); 70 | cin.sync_with_stdio(0); 71 | 72 | string s = "banana"; 73 | 74 | auto sa = suf_con(s); 75 | 76 | for(int i = 0; i < int(s.size()); ++i) 77 | cout << sa[i] << ' ' << s.substr(sa[i], s.size()) << endl; 78 | } 79 | -------------------------------------------------------------------------------- /CPP/suffix_automaton.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using ll = long long; 3 | using namespace std; 4 | 5 | struct node { 6 | int len; 7 | node *suf; 8 | bool terminal = false; 9 | map kids; 10 | 11 | node(int lenn, node *suff) { 12 | len = lenn; 13 | suf = suff; 14 | } 15 | 16 | node(node *src) { 17 | len = src->len; 18 | suf = src->suf; 19 | kids = src->kids; 20 | } 21 | }; 22 | 23 | struct sa { 24 | node *last; 25 | node *root; 26 | vector stash; 27 | 28 | sa() { 29 | root = new node(0, 0); 30 | root->suf = root; 31 | last = root; 32 | } 33 | 34 | sa(string const &s) : sa() { 35 | for (char c : s) add(c); 36 | } 37 | 38 | ~sa() { 39 | for (auto x : stash) delete x; 40 | } 41 | 42 | void add(char c) { 43 | auto cur = new node(last->len + 1, root); 44 | stash.emplace_back(cur); 45 | auto p = last; 46 | while (p->kids.find(c) == p->kids.end()) { 47 | p->kids[c] = cur; 48 | p = p->suf; 49 | } 50 | auto q = p->kids[c]; 51 | if (q != cur) { 52 | if (p->len + 1 == q->len) { 53 | cur->suf = q; 54 | } else { 55 | auto clone = new node(q); 56 | stash.emplace_back(clone); 57 | clone->suf = root; 58 | clone->len = p->len + 1; 59 | cur->suf = q->suf = clone; 60 | while (p->kids[c] == q) { 61 | p->kids[c] = clone; 62 | p = p->suf; 63 | } 64 | } 65 | } 66 | last = cur; 67 | } 68 | 69 | void mark_ends() { 70 | auto p = last; 71 | while (not p->terminal) { 72 | p->terminal = true; 73 | p = p->suf; 74 | } 75 | } 76 | 77 | bool find(string const &s) { 78 | auto p = root; 79 | for (char c : s) { 80 | auto f = p->kids.find(c); 81 | if (f == p->kids.end()) return false; 82 | p = f->second; 83 | } 84 | return true; 85 | } 86 | }; 87 | 88 | int main() { 89 | cin.tie(0); 90 | cin.sync_with_stdio(0); 91 | 92 | sa a("basselbakr"); 93 | } 94 | -------------------------------------------------------------------------------- /CPP/suffix_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | using ll = long long; 4 | 5 | int inf = 1000 * 1000 * 1000; 6 | 7 | int tot; 8 | int step; 9 | int eds; 10 | int suffs; 11 | 12 | struct node; 13 | 14 | struct edge { 15 | int l, r; 16 | node *dest; 17 | 18 | edge(int ls, int rs, node *to) { 19 | l = ls; 20 | r = rs; 21 | dest = to; 22 | eds++; 23 | } 24 | 25 | edge(edge *other) : edge(other->l, other->r, other->dest) {} 26 | }; 27 | 28 | struct node { 29 | node *suffix; 30 | map kids; 31 | 32 | node() { 33 | tot++; 34 | suffix = 0; 35 | } 36 | }; 37 | 38 | struct suffix_tree { 39 | int rem = 0; 40 | int ac_pos = 0; 41 | edge *ac_edge = 0; 42 | node *ac_node = 0; 43 | 44 | string s; 45 | node *root = 0; 46 | 47 | suffix_tree(string const &ss) { 48 | s = ss; 49 | root = new node(); 50 | ac_node = root; 51 | ac_edge = 0; 52 | ac_pos = 0; 53 | for (int i = 0; i < s.size(); ++i) add(i, s[i]); 54 | } 55 | 56 | ~suffix_tree() { 57 | vector del{root}; 58 | while (del.size()) { 59 | auto u = del.back(); 60 | del.pop_back(); 61 | for (auto [ignore, edge] : u->kids) { 62 | if (edge->dest) del.emplace_back(edge->dest); 63 | delete edge; 64 | } 65 | delete u; 66 | } 67 | } 68 | 69 | void add(int i, char c) { 70 | rem++; 71 | node *prev = 0; 72 | while (rem) { 73 | step++; 74 | if (ac_edge) { 75 | if (c == s[ac_edge->l + ac_pos + 1]) { 76 | ac_pos++; 77 | if (ac_edge->l + ac_pos + 1 > ac_edge->r) { 78 | ac_node = ac_edge->dest; 79 | ac_edge = 0; 80 | } 81 | break; 82 | } else { 83 | rem--; 84 | auto ec = new edge(ac_edge); 85 | ec->l += ac_pos + 1; 86 | ac_edge->r += ec->l; 87 | 88 | auto nod = new node(); 89 | ac_edge->dest = nod; 90 | nod->kids[c] = new edge(i, inf, 0); 91 | nod->kids[s[ac_edge->l + ac_pos]] = ec; 92 | 93 | if (prev) { 94 | suffs++; 95 | prev->suffix = nod; 96 | } 97 | prev = nod; 98 | 99 | if (ac_node->suffix) { 100 | ac_node = ac_node->suffix; 101 | ac_edge = ac_node->kids[s[ac_edge->l]]; 102 | } else if (ac_node != root) { 103 | ac_node = root; 104 | ac_edge = ac_node->kids[s[ac_edge->l + ac_pos]]; 105 | } else { 106 | ac_edge = (ac_pos > 0 ? ac_node->kids[s[ac_edge->l + --ac_pos]] : 0); 107 | } 108 | } 109 | } else { 110 | auto &e = ac_node->kids[c]; 111 | if (e) { 112 | ac_edge = e; 113 | ac_pos = 0; 114 | if (ac_edge->l + ac_pos + 1 > ac_edge->r) { 115 | ac_node = ac_edge->dest; 116 | ac_edge = 0; 117 | } 118 | break; 119 | } else { 120 | rem--; 121 | e = new edge(i, inf, 0); 122 | if (ac_node->suffix) { 123 | ac_node = ac_node->suffix; 124 | ac_edge = 0; 125 | } else { 126 | ac_node = root; 127 | ac_edge = 0; 128 | } 129 | } 130 | } 131 | } 132 | } 133 | }; 134 | 135 | int main() { 136 | string s = "abcabxabcd$"; 137 | 138 | suffix_tree st(s); 139 | 140 | cout << "Nodes: " << tot << "\n" 141 | << "Edges: " << eds << "\n" 142 | << "Links: " << suffs << "\n" 143 | << "Steps: " << step + 1 << "\n"; 144 | } 145 | -------------------------------------------------------------------------------- /CPP/wavelet_matrix.cpp: -------------------------------------------------------------------------------- 1 | #include "bits/stdc++.h" 2 | using namespace std; 3 | using ll = long long; 4 | 5 | struct wavelet_matrix { 6 | int n; 7 | uint mask; 8 | uint logn; 9 | vector z; 10 | vector> s; 11 | vector> b[2]; 12 | 13 | template 14 | wavelet_matrix(Iter pl, Iter pr) { 15 | auto tmp = vector(pl, pr); 16 | n = int(tmp.size()); 17 | mask = ~0u; 18 | logn = 32; 19 | z.resize(logn); 20 | b[0].assign(logn + 1, vector(n + 1)); 21 | b[1].assign(logn + 1, vector(n + 1)); 22 | s.assign(logn + 1, vector(n + 1)); 23 | for (int j = logn; j >= 0; --j) { 24 | int cnt[2] = {}; 25 | auto& zero = b[0][j]; 26 | auto& one = b[1][j]; 27 | auto f = [j](int x) { return (((x ^ (1u << 31)) >> (j - 1)) & 1) ^ 1; }; 28 | for (int i = 0; i < n; ++i) { 29 | if (j) cnt[f(tmp[i]) ^ 1] += 1; 30 | zero[i + 1] = cnt[0]; 31 | one[i + 1] = cnt[1]; 32 | s[j][i + 1] = s[j][i] + tmp[i]; 33 | } 34 | z[j] = cnt[0]; 35 | if (j) stable_partition(tmp.begin(), tmp.end(), f); 36 | } 37 | } 38 | 39 | int sum(int l, int r, uint a, uint b) { 40 | return sum(logn, l, r + 1, a ^ (1u << 31), b ^ (1u << 31), 0, mask); 41 | } 42 | 43 | // [l, r) 44 | int sum(int i, int l, int r, uint a, uint t, uint A, uint Z) { 45 | if (l >= r) { 46 | return 0; 47 | } 48 | 49 | if (a <= A && Z <= t) { 50 | return s[i][r] - s[i][l]; 51 | } 52 | 53 | uint mid = A + (Z - A) / 2; 54 | int x = 0; 55 | if (a <= mid) x += sum(i - 1, b[0][i][l], b[0][i][r], a, t, A, mid); 56 | if (mid < t) 57 | x += sum(i - 1, z[i] + b[1][i][l], z[i] + b[1][i][r], a, t, mid + 1, Z); 58 | return x; 59 | } 60 | 61 | int kth(int l, int r, int k) { return kth(logn, l, r + 1, k, 0, mask); } 62 | 63 | int kth(int i, int l, int r, int k, uint A, uint Z) { 64 | if (A == Z) return A ^ (1u << 31); 65 | uint mid = A + (Z - A) / 2; 66 | int zeros = b[0][i][r] - b[0][i][l]; 67 | if (k <= zeros) 68 | return kth(i - 1, b[0][i][l], b[0][i][r], k, A, mid); 69 | else 70 | return kth(i - 1, z[i] + b[1][i][l], z[i] + b[1][i][r], k - zeros, 71 | mid + 1, Z); 72 | } 73 | }; 74 | 75 | int main() { 76 | cin.tie(0); 77 | cin.sync_with_stdio(0); 78 | 79 | int n = 8; 80 | auto a = vector(n); 81 | iota(a.begin(), a.end(), -5); 82 | 83 | wavelet_matrix wm(a.begin(), a.end()); 84 | 85 | cout << wm.sum(0, n - 1, -5, 0) << endl; 86 | 87 | for (int i = 0; i < n; ++i) { 88 | cout << wm.kth(0, n - 1, i + 1) << endl; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Clojure/treap.clj: -------------------------------------------------------------------------------- 1 | (ns treap 2 | (:refer-clojure 3 | :exclude [print remove rand])) 4 | 5 | (defn- rand [] 6 | (rand-int Integer/MAX_VALUE)) 7 | 8 | (defrecord node [x y s l r]) 9 | 10 | (defn- new-node [x] 11 | (->node x (rand) 1 nil nil)) 12 | 13 | (defn size [{s :s}] 14 | (or s 0)) 15 | 16 | (defn join 17 | ([{y1 :y s1 :s r1 :r :as lf} 18 | {y2 :y l2 :l s2 :s :as rg}] 19 | (cond 20 | (nil? lf) rg 21 | (nil? rg) lf 22 | (< y1 y2) 23 | (assoc lf 24 | :r (join r1 rg) 25 | :s (inc s1)) 26 | :else 27 | (assoc rg 28 | :l (join lf l2) 29 | :s (inc s2)))) 30 | ([a b & c] 31 | (reduce join (join a b) c))) 32 | 33 | (defn split [{:keys [x l r] :as p} v] 34 | (cond 35 | (nil? p) 36 | [nil nil] 37 | (< v x) 38 | (let [[lf rg] (split l v)] 39 | [lf 40 | (assoc p 41 | :l rg 42 | :s (+ (size rg) 1 (size r)))]) 43 | :else 44 | (let [[lf rg] (split r v)] 45 | [(assoc p 46 | :r lf 47 | :s (+ (size l) 1 (size lf))) 48 | rg]))) 49 | 50 | (defn insert [p v] 51 | (let [[l r] (split p v)] 52 | (join l (new-node v) r))) 53 | 54 | (defn remove [{:keys [x s l r] :as p} v] 55 | (cond 56 | (nil? p) nil 57 | (< v x) 58 | (let [l (remove l v)] 59 | (assoc p 60 | :l l 61 | :s (+ (size l) 1 (size r)))) 62 | (> v x) 63 | (let [r (remove r v)] 64 | (assoc p 65 | :r r 66 | :s (+ (size l) 1 (size r)))) 67 | :else (join l r))) 68 | 69 | (defn remove-range [p l r] 70 | (let [[a b] (split p r)] 71 | (let [[x y] (split a (- l 1))] 72 | (join x b)))) 73 | 74 | (defn print [{:keys [x l r] :as p}] 75 | (lazy-seq 76 | (if (nil? p) 77 | nil 78 | (concat (print l) 79 | (list x) 80 | (print r))))) 81 | 82 | (defn make-treap [a] 83 | (loop [t nil [f & r] a] 84 | (if (nil? f) 85 | t 86 | (recur (insert t f) r)))) 87 | -------------------------------------------------------------------------------- /Go/treap.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "cmp" 5 | "math/rand/v2" 6 | ) 7 | 8 | type Node[T cmp.Ordered] struct { 9 | Value T 10 | heapValue int 11 | Left, Right *Node[T] 12 | } 13 | 14 | func NewNode[T cmp.Ordered](x T) *Node[T] { 15 | return &Node[T]{ 16 | Value: x, 17 | heapValue: rand.Int(), 18 | } 19 | } 20 | 21 | func (left *Node[T]) join(right *Node[T]) *Node[T] { 22 | if left == nil { 23 | return right 24 | } else if right == nil { 25 | return left 26 | } else if left.heapValue < right.heapValue { 27 | left.Right = left.Right.join(right) 28 | return left 29 | } else { 30 | right.Left = left.join(right.Left) 31 | return right 32 | } 33 | } 34 | 35 | func (node *Node[T]) split(value T) (*Node[T], *Node[T]) { 36 | if node == nil { 37 | return nil, nil 38 | } else if cmp.Compare(value, node.Value) < 0 { 39 | leftLeft, leftRight := node.Left.split(value) 40 | node.Left = leftRight 41 | return leftLeft, node 42 | } else { 43 | rightLeft, rightRight := node.Right.split(value) 44 | node.Right = rightLeft 45 | return node, rightRight 46 | } 47 | } 48 | 49 | func (node *Node[T]) insert(value T) *Node[T] { 50 | left, right := node.split(value) 51 | return left.join(NewNode(value)).join(right) 52 | } 53 | 54 | func (node *Node[T]) print() { 55 | if node == nil { 56 | return 57 | } 58 | node.Left.print() 59 | println(node.Value) 60 | node.Right.print() 61 | } 62 | 63 | func main() { 64 | var t *Node[int] 65 | 66 | for i := range 100_000 { 67 | t = t.insert(i) 68 | } 69 | 70 | t.print() 71 | } 72 | -------------------------------------------------------------------------------- /Kotlin/Treap.kt: -------------------------------------------------------------------------------- 1 | class Treap { 2 | data class Node(var x: Int, 3 | var l: Node? = null, 4 | var r: Node? = null, 5 | var s: Int = 1, 6 | val y: Int = (Math.random() * 100_000).toInt()) 7 | 8 | fun Node.upd(): Node { 9 | s = 1 10 | s += l?.s ?: 0 11 | s += r?.s ?: 0 12 | return this 13 | } 14 | 15 | var root: Node? = null 16 | 17 | fun join(l: Node?, r: Node?) : Node? { 18 | if(l == null) return r 19 | if(r == null) return l 20 | 21 | if(l.y < r.y) { 22 | l.r = join(l.r, r) 23 | return l.upd() 24 | } else { 25 | r.l = join(l, r.l) 26 | return r.upd() 27 | } 28 | } 29 | 30 | fun split(p: Node?, x: Int): Pair { 31 | return if(p == null) 32 | Pair(null, null) 33 | else if(x < p.x) { 34 | var (l, r) = split(p.l, x) 35 | p.l = r 36 | r = p.upd() 37 | Pair(l, r) 38 | } else { 39 | var (l, r) = split(p.r, x) 40 | p.r = l 41 | l = p.upd() 42 | Pair(l, r) 43 | } 44 | } 45 | 46 | fun insert(x: Int) { 47 | val (l, r) = split(root, x) 48 | root = join(l, join(Node(x), r)) 49 | } 50 | 51 | fun remove(x: Int) { 52 | root = remove(root, x) 53 | } 54 | 55 | fun print(): Int { 56 | return print(root) 57 | } 58 | 59 | fun remove(p: Node?, x: Int): Node? { 60 | if(p == null) 61 | return null 62 | 63 | if(x == p.x) 64 | return join(p.l, p.r) 65 | 66 | if(x < p.x) 67 | p.l = remove(p.l, x) 68 | else 69 | p.r = remove(p.r, x) 70 | 71 | return p.upd() 72 | } 73 | 74 | fun print(p: Node?): Int { 75 | if(p == null) 76 | return 0 77 | 78 | val l = print(p.l) 79 | println(p.x) 80 | val r = print(p.r) 81 | 82 | return 1 + Math.max(l, r) 83 | } 84 | } 85 | 86 | fun main(args: Array) { 87 | val n = 100 88 | val t = Treap() 89 | 90 | for(i in 0 until n) 91 | t.insert(i) 92 | 93 | t.print() 94 | } 95 | -------------------------------------------------------------------------------- /Python/Treap.py: -------------------------------------------------------------------------------- 1 | from random import randrange as rand 2 | 3 | class Node: 4 | def __init__(self, x): 5 | self.x = x 6 | self.y = rand(1000000000) 7 | self.l = self.r = None 8 | 9 | class Treap: 10 | def __init__(self): 11 | self.root = None 12 | 13 | # join two trees O(log n) 14 | def join(self, l, r): 15 | if not l: return r 16 | if not r: return l 17 | 18 | if l.y < r.y: 19 | l.r = self.join(l.r, r) 20 | return l 21 | else: 22 | r.l = self.join(l, r.l) 23 | return r 24 | 25 | # split into two trees O(log n) 26 | def split(self, x, p): 27 | if not p: 28 | return (None, None) 29 | 30 | if x < p.x: 31 | l, r = self.split(x, p.l) 32 | p.l = r 33 | return (l, p); 34 | else: 35 | l, r = self.split(x, p.r) 36 | p.r = l 37 | return (p, r) 38 | 39 | # O(log n) 40 | def insert(self, x): 41 | l, r = self.split(x, self.root) 42 | self.root = self.join(l, self.join(Node(x), r)) 43 | 44 | # delete one element O(log n) 45 | def delete(self, x): 46 | l, r = self.split(x, self.root) 47 | l2, r2 = self.split(x-1, l) 48 | l = self.join(l2, self.join(r2.l, r2.r) if r2 else None) 49 | self.root = self.join(l, r) 50 | 51 | # delete range of elements O(log n) 52 | def delete(self, L, R): 53 | l, r = self.split(R, self.root) 54 | l2, r2 = self.split(L-1, l) 55 | self.root = self.join(l2, r) 56 | 57 | # O(log n) 58 | def find(self, x): 59 | p = self.root 60 | while p: 61 | if x == p.x: 62 | return True 63 | 64 | if x < p.x: 65 | p = p.l 66 | else: 67 | p = p.r 68 | return False 69 | 70 | # O(n) 71 | def inorder(self, p, level, view): 72 | if not p: return level 73 | l = self.inorder(p.l, level + 1, view) 74 | if view: print(p.x) 75 | r = self.inorder(p.r, level + 1, view) 76 | return max(l, r) 77 | 78 | # O(n) 79 | def disply(self, view = True): 80 | return self.inorder(self.root, 0, view) 81 | 82 | t = Treap() 83 | for i in range(10000): 84 | t.insert(i) 85 | 86 | t.delete(6, 9994) 87 | print("Levels: %d" % t.disply()) 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data_Structures 2 | -------------------------------------------------------------------------------- /Rust/Treap.rs: -------------------------------------------------------------------------------- 1 | extern "C" { 2 | fn rand() -> u32; 3 | } 4 | 5 | fn get_rand() -> u32 { 6 | unsafe { rand() } 7 | } 8 | 9 | type TreeNode = Option>>; 10 | 11 | struct Node { 12 | value: T, 13 | height: u32, 14 | size: usize, 15 | left: Option>>, 16 | right: Option>>, 17 | } 18 | 19 | impl Node { 20 | fn new(x: T) -> Node { 21 | Node { 22 | value: x, 23 | height: get_rand(), 24 | size: 1usize, 25 | left: None, 26 | right: None, 27 | } 28 | } 29 | 30 | fn boxed(x: T) -> Box> { 31 | let node = Node::new(x); 32 | Box::new(node) 33 | } 34 | 35 | fn wrap(x: T) -> Option>> { 36 | Some(Node::boxed(x)) 37 | } 38 | 39 | fn update(&mut self) { 40 | let left_size = self.left.as_ref().map_or(0, |node| node.size); 41 | let right_size = self.right.as_ref().map_or(0, |node| node.size); 42 | 43 | self.size = left_size + 1 + right_size; 44 | } 45 | } 46 | 47 | struct Tree { 48 | root: TreeNode, 49 | } 50 | 51 | impl Tree { 52 | fn new() -> Tree { 53 | Tree { root: None } 54 | } 55 | 56 | fn insert(&mut self, x: T) { 57 | let (left, right) = Tree::split(self.root.take(), &x); 58 | self.root = Tree::join(left, Tree::join(Node::wrap(x), right)); 59 | } 60 | 61 | fn join(mut left: TreeNode, mut right: TreeNode) -> TreeNode { 62 | match (&mut left, &mut right) { 63 | (None, _) => right, 64 | (_, None) => left, 65 | (Some(ref mut lf), Some(ref mut rg)) => { 66 | if lf.height > rg.height { 67 | lf.right = Tree::join(lf.right.take(), right); 68 | lf.update(); 69 | left 70 | } else { 71 | rg.left = Tree::join(left, rg.left.take()); 72 | rg.update(); 73 | right 74 | } 75 | } 76 | } 77 | } 78 | 79 | fn split(mut node: TreeNode, value: &T) -> (TreeNode, TreeNode) { 80 | match &mut node { 81 | None => (None, None), 82 | Some(ref mut p) => { 83 | if value < &p.value { 84 | let (lf, rg) = Tree::split(p.left.take(), value); 85 | p.left = rg; 86 | p.update(); 87 | (lf, node) 88 | } else { 89 | let (lf, rg) = Tree::split(p.right.take(), value); 90 | p.right = lf; 91 | p.update(); 92 | (node, rg) 93 | } 94 | } 95 | } 96 | } 97 | 98 | fn size(&self) -> usize { 99 | return self.root.as_ref().map_or(0, |node| node.size); 100 | } 101 | } 102 | 103 | fn main() { 104 | let mut t = Tree::new(); 105 | 106 | for i in 1..1000_000 { 107 | t.insert(i); 108 | } 109 | 110 | println!("{}", t.size()); 111 | } 112 | -------------------------------------------------------------------------------- /Rust/UnionFind.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut uf = data_structures::UnionFind::new(45); 3 | } 4 | 5 | mod data_structures { 6 | use std::mem; 7 | 8 | pub struct UnionFind { 9 | fa: Vec, 10 | } 11 | 12 | impl UnionFind { 13 | pub fn new(n: usize) -> UnionFind { 14 | UnionFind { 15 | fa: vec![-1isize; n], 16 | } 17 | } 18 | 19 | pub fn find(&mut self, mut x: usize) -> usize { 20 | let mut p = x; 21 | while !self.fa[p].is_negative() { 22 | p = self.fa[p] as usize; 23 | } 24 | while !self.fa[x].is_negative() { 25 | x = mem::replace(&mut self.fa[x], p as isize) as usize; 26 | } 27 | p 28 | } 29 | 30 | pub fn union(&mut self, x: usize, y: usize) -> bool { 31 | let x = self.find(x); 32 | let y = self.find(y); 33 | if x == y { 34 | false 35 | } else { 36 | self.fa[x] += self.fa[y]; 37 | self.fa[y] = x as isize; 38 | true 39 | } 40 | } 41 | 42 | pub fn size(&mut self, x: usize) -> usize { 43 | let p = self.find(x); 44 | (-self.fa[p]) as usize 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Rust/splay.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | #![allow(unused_variables, unused_imports)] 3 | 4 | use std::cell::RefCell; 5 | use std::cmp; 6 | use std::io::*; 7 | use std::rc::{Rc, Weak}; 8 | use std::{mem, mem::ManuallyDrop}; 9 | 10 | fn main() { 11 | // let input = &mut Input::new(); 12 | // let output = &mut BufWriter::new(stdout()); 13 | let mut t = Tree::new(); 14 | for i in 0..1000_000 { 15 | t.insert(unsafe { rand() }); 16 | } 17 | } 18 | 19 | extern "C" { 20 | fn rand() -> i32; 21 | } 22 | 23 | type Branch = Option>>>>; 24 | type Parent = Option>>>>; 25 | 26 | struct Node { 27 | x: T, 28 | l: Branch, 29 | r: Branch, 30 | p: Parent, 31 | } 32 | 33 | impl Node { 34 | fn new(x: T) -> Self { 35 | Node { 36 | x: x, 37 | l: None, 38 | r: None, 39 | p: None, 40 | } 41 | } 42 | 43 | fn new_branch(x: T) -> Branch { 44 | Some(Rc::new(ManuallyDrop::new(RefCell::new(Node::new(x))))) 45 | } 46 | } 47 | 48 | struct Tree { 49 | root: Branch, 50 | } 51 | 52 | impl Drop for Tree { 53 | fn drop(&mut self) { 54 | let root = mem::take(&mut self.root); 55 | let mut a = Vec::new(); 56 | a.push(root); 57 | 58 | while let Some(mut p) = a.pop() { 59 | let l = mem::take(&mut p.as_ref().unwrap().borrow_mut().l); 60 | let r = mem::take(&mut p.as_ref().unwrap().borrow_mut().r); 61 | 62 | let mut x = Rc::get_mut(p.as_mut().unwrap()); 63 | if x.is_some() { 64 | unsafe { 65 | ManuallyDrop::drop(x.as_mut().unwrap()); 66 | } 67 | } else { 68 | a.push(p); 69 | } 70 | 71 | if l.is_some() { 72 | a.push(l); 73 | } 74 | 75 | if r.is_some() { 76 | a.push(r); 77 | } 78 | } 79 | } 80 | } 81 | 82 | impl Tree { 83 | fn new() -> Self { 84 | Tree { root: None } 85 | } 86 | 87 | fn insert(&mut self, x: T) { 88 | let (l, r) = Self::split(mem::take(&mut self.root), &x); 89 | let node = Node::new_branch(x); 90 | { 91 | let mut m = node.as_ref().unwrap().borrow_mut(); 92 | if l.is_some() { 93 | l.as_ref().unwrap().borrow_mut().p = Some(Rc::downgrade(node.as_ref().unwrap())); 94 | m.l = l; 95 | } 96 | if r.is_some() { 97 | r.as_ref().unwrap().borrow_mut().p = Some(Rc::downgrade(node.as_ref().unwrap())); 98 | m.r = r; 99 | } 100 | } 101 | self.root = node; 102 | } 103 | 104 | fn split(root: Branch, x: &T) -> (Branch, Branch) { 105 | if root.is_none() { 106 | (None, None) 107 | } else { 108 | let mut p = Rc::clone(root.as_ref().unwrap()); 109 | let mut left; 110 | 111 | loop { 112 | if x < &p.borrow().x { 113 | left = false; 114 | if p.borrow().l.is_some() { 115 | p = { 116 | let b = p.borrow(); 117 | Rc::clone(b.l.as_ref().unwrap()) 118 | } 119 | } else { 120 | break; 121 | } 122 | } else { 123 | left = true; 124 | if p.borrow().r.is_some() { 125 | p = { 126 | let b = p.borrow(); 127 | Rc::clone(b.r.as_ref().unwrap()) 128 | } 129 | } else { 130 | break; 131 | } 132 | } 133 | } 134 | 135 | if left { 136 | let l = Some(p); 137 | Self::splay(&l); 138 | let r = mem::take(&mut l.as_ref().unwrap().borrow_mut().r); 139 | if r.is_some() { 140 | r.as_ref().unwrap().borrow_mut().p = None; 141 | } 142 | 143 | (l, r) 144 | } else { 145 | let r = Some(p); 146 | Self::splay(&r); 147 | let l = mem::take(&mut r.as_ref().unwrap().borrow_mut().l); 148 | if l.is_some() { 149 | l.as_ref().unwrap().borrow_mut().p = None; 150 | } 151 | 152 | (l, r) 153 | } 154 | } 155 | } 156 | 157 | fn join(l: Branch, r: Branch) -> Branch { 158 | match (l.as_ref(), r.as_ref()) { 159 | (None, _) => r, 160 | (_, None) => l, 161 | _ => { 162 | // splay rightmost node in `l` 163 | let mut p = Rc::clone(l.as_ref().unwrap()); 164 | while p.borrow().r.is_some() { 165 | p = { 166 | let pm = p.borrow(); 167 | Rc::clone(pm.r.as_ref().unwrap()) 168 | } 169 | } 170 | 171 | r.as_ref().unwrap().borrow_mut().p = Some(Rc::downgrade(&p)); 172 | let root = Some(p); 173 | Self::splay(&root); 174 | root.as_ref().unwrap().borrow_mut().r = r; 175 | root 176 | } 177 | } 178 | } 179 | 180 | fn is_left(c: &Branch) -> bool { 181 | let me = c.as_ref().unwrap().borrow(); 182 | if me.p.is_some() { 183 | let pp = me.p.as_ref().unwrap().upgrade(); 184 | if pp.is_none() { 185 | return false; 186 | } 187 | let up = pp.as_ref().unwrap().borrow(); 188 | up.l.is_some() && Rc::ptr_eq(c.as_ref().unwrap(), up.l.as_ref().unwrap()) 189 | } else { 190 | false 191 | } 192 | } 193 | 194 | fn splay(c: &Branch) -> &Branch { 195 | while c.as_ref().unwrap().borrow().p.is_some() { 196 | let p = c.as_ref().unwrap().borrow().p.as_ref().unwrap().upgrade(); 197 | let rot_parent = { 198 | let g = &p.as_ref().unwrap().borrow().p; 199 | 200 | g.is_some() && (Self::is_left(c) == Self::is_left(&p)) 201 | }; 202 | 203 | if rot_parent { 204 | Self::rot(&p); 205 | } 206 | 207 | Self::rot(c); 208 | } 209 | c 210 | } 211 | 212 | fn rot(c: &Branch) -> &Branch { 213 | // get the parent 214 | let mut p = c.as_ref().unwrap().borrow().p.as_ref().unwrap().upgrade(); 215 | 216 | // where is grandpa? 217 | let g = { 218 | let node = p.as_ref().unwrap().borrow(); 219 | 220 | match node.p.as_ref() { 221 | Some(weak_g) => weak_g.upgrade(), 222 | _ => None, 223 | } 224 | }; 225 | 226 | let is_left_parent = Self::is_left(&p); 227 | 228 | // ignore the grandpa now 229 | let is_left_child = Self::is_left(c); 230 | 231 | if is_left_child { 232 | let mut cm = c.as_ref().unwrap().borrow_mut(); 233 | { 234 | let mut pm = p.as_ref().unwrap().borrow_mut(); 235 | let kid = mem::take(&mut cm.r); 236 | if kid.is_some() { 237 | kid.as_ref().unwrap().borrow_mut().p = Some(Rc::downgrade(p.as_ref().unwrap())); 238 | } 239 | cm.p = mem::replace(&mut pm.p, Some(Rc::downgrade(c.as_ref().unwrap()))); 240 | if g.is_some() { 241 | if is_left_parent { 242 | g.as_ref().unwrap().borrow_mut().l = mem::take(&mut pm.l); 243 | } else { 244 | g.as_ref().unwrap().borrow_mut().r = mem::take(&mut pm.l); 245 | } 246 | } 247 | pm.l = kid; 248 | } 249 | cm.r = mem::take(&mut p); 250 | } else { 251 | let mut cm = c.as_ref().unwrap().borrow_mut(); 252 | { 253 | let mut pm = p.as_ref().unwrap().borrow_mut(); 254 | let kid = mem::take(&mut cm.l); 255 | if kid.is_some() { 256 | kid.as_ref().unwrap().borrow_mut().p = Some(Rc::downgrade(p.as_ref().unwrap())); 257 | } 258 | cm.p = mem::replace(&mut pm.p, Some(Rc::downgrade(c.as_ref().unwrap()))); 259 | if g.is_some() { 260 | if is_left_parent { 261 | g.as_ref().unwrap().borrow_mut().l = mem::take(&mut pm.r); 262 | } else { 263 | g.as_ref().unwrap().borrow_mut().r = mem::take(&mut pm.r); 264 | } 265 | } 266 | pm.r = kid; 267 | } 268 | cm.l = mem::take(&mut p); 269 | } 270 | 271 | c 272 | } 273 | } 274 | 275 | //{{{ 276 | struct Input { 277 | buf: Vec, 278 | } 279 | 280 | impl Input { 281 | fn new() -> Self { 282 | Input { buf: Vec::new() } 283 | } 284 | 285 | fn next(&mut self) -> T { 286 | if self.buf.is_empty() { 287 | self.buf = self 288 | .next_line() 289 | .split_whitespace() 290 | .rev() 291 | .map(String::from) 292 | .collect(); 293 | } 294 | 295 | self.buf.pop().unwrap().parse().ok().expect("err") 296 | } 297 | 298 | fn next_line(&mut self) -> String { 299 | let mut line = String::new(); 300 | stdin().read_line(&mut line).expect("read err"); 301 | line 302 | } 303 | } //}}} 304 | --------------------------------------------------------------------------------