rbtree 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. #ifndef __GBLIBCPP_BITS_RBTREE__
  2. #define __GBLIBCPP_BITS_RBTREE__
  3. #include "compressed_pair"
  4. #include <cstddef>
  5. #include <functional>
  6. #include <utility>
  7. #include <memory>
  8. namespace std::impl {
  9. template <typename T, typename Compare, typename Allocator>
  10. struct rbtree {
  11. struct node {
  12. node* parent;
  13. node* left;
  14. node* right;
  15. T value;
  16. enum class node_color : unsigned char { RED, BLACK, } color;
  17. constexpr node(const T& val)
  18. : parent {}, left {}, right {}
  19. , value { val } , color {node_color::RED} {}
  20. constexpr node(T&& val)
  21. : parent {}, left {}, right {}
  22. , value { std::move(val) } , color {node_color::RED} {}
  23. template <typename... Args, std::enable_if_t<
  24. (sizeof...(Args) > 1)
  25. || !(... && std::is_same_v<T, std::remove_cvref_t<Args>>)
  26. , bool> = true>
  27. constexpr node(Args&&... args)
  28. : parent {}, left {}, right {}
  29. , value { std::forward<Args>(args)... }, color { node_color::RED } {}
  30. constexpr node* grandparent(void) const
  31. { return this->parent->parent; }
  32. constexpr node* uncle(void) const
  33. {
  34. node* pp = this->grandparent();
  35. if (this->parent == pp->left)
  36. return pp->right;
  37. return pp->left;
  38. }
  39. constexpr node* leftmost(void)
  40. {
  41. node* nd = this;
  42. while (nd->left)
  43. nd = nd->left;
  44. return nd;
  45. }
  46. constexpr node* rightmost(void)
  47. {
  48. node* nd = this;
  49. while (nd->right)
  50. nd = nd->right;
  51. return nd;
  52. }
  53. constexpr node* next(void)
  54. {
  55. if (this->right)
  56. return this->right->leftmost();
  57. if (this->is_root())
  58. return nullptr;
  59. if (this->is_left_child())
  60. return this->parent;
  61. node* ret = this;
  62. do {
  63. ret = ret->parent;
  64. } while (!ret->is_root() && !ret->is_left_child());
  65. return ret->parent;
  66. }
  67. constexpr node* prev(void)
  68. {
  69. if (this->left)
  70. return this->left->rightmost();
  71. if (this->is_root())
  72. return nullptr;
  73. if (this->is_right_child())
  74. return this->parent;
  75. node* ret = this;
  76. do {
  77. ret = ret->parent;
  78. } while (!ret->is_root() && !ret->is_right_child());
  79. return ret->parent;
  80. }
  81. static constexpr bool is_red(node* nd)
  82. { return nd && nd->color == node_color::RED; }
  83. static constexpr bool is_black(node* nd)
  84. { return !node::is_red(nd); }
  85. constexpr bool is_root(void) const
  86. { return this->parent == nullptr; }
  87. constexpr bool is_full(void) const
  88. { return this->left && this->right; }
  89. constexpr bool has_child(void) const
  90. { return this->left || this->right; }
  91. constexpr bool is_leaf(void) const
  92. { return !this->has_child(); }
  93. constexpr bool is_left_child(void) const
  94. { return this == this->parent->left; }
  95. constexpr bool is_right_child(void) const
  96. { return this == this->parent->right; }
  97. constexpr void tored(void)
  98. { this->color = node_color::RED; }
  99. constexpr void toblack(void)
  100. { this->color = node_color::BLACK; }
  101. static constexpr void swap(node* first, node* second)
  102. {
  103. if (node::is_red(first)) {
  104. first->color = second->color;
  105. second->color = node_color::RED;
  106. } else {
  107. first->color = second->color;
  108. second->color = node_color::BLACK;
  109. }
  110. if (first->parent == second) {
  111. node* tmp = first;
  112. first = second;
  113. second = tmp;
  114. }
  115. bool f_is_left_child = first->parent ? first->is_left_child() : false;
  116. bool s_is_left_child = second->parent ? second->is_left_child() : false;
  117. node* fp = first->parent;
  118. node* fl = first->left;
  119. node* fr = first->right;
  120. node* sp = second->parent;
  121. node* sl = second->left;
  122. node* sr = second->right;
  123. if (second->parent != first) {
  124. first->parent = sp;
  125. if (sp) {
  126. if (s_is_left_child)
  127. sp->left = first;
  128. else
  129. sp->right = first;
  130. }
  131. first->left = sl;
  132. if (sl)
  133. sl->parent = first;
  134. first->right = sr;
  135. if (sr)
  136. sr->parent = first;
  137. second->parent = fp;
  138. if (fp) {
  139. if (f_is_left_child)
  140. fp->left = second;
  141. else
  142. fp->right = second;
  143. }
  144. second->left = fl;
  145. if (fl)
  146. fl->parent = second;
  147. second->right = fr;
  148. if (fr)
  149. fr->parent = second;
  150. } else {
  151. first->left = sl;
  152. if (sl)
  153. sl->parent = first;
  154. first->right = sr;
  155. if (sr)
  156. sr->parent = first;
  157. second->parent = fp;
  158. if (fp) {
  159. if (f_is_left_child)
  160. fp->left = second;
  161. else
  162. fp->right = second;
  163. }
  164. first->parent = second;
  165. if (s_is_left_child) {
  166. second->left = first;
  167. second->right = fr;
  168. if (fr)
  169. fr->parent = second;
  170. } else {
  171. second->right = first;
  172. second->left = fl;
  173. if (fl)
  174. fl->parent = second;
  175. }
  176. }
  177. }
  178. };
  179. template <bool Const>
  180. class _iterator {
  181. public:
  182. using node_pointer = node*;
  183. using value_type = std::conditional_t<Const, const T, T>;
  184. using pointer = std::add_pointer_t<value_type>;
  185. using reference = std::add_lvalue_reference_t<value_type>;
  186. friend rbtree;
  187. private:
  188. node_pointer p;
  189. public:
  190. constexpr _iterator() = default;
  191. explicit constexpr _iterator(node_pointer ptr)
  192. : p { ptr } {}
  193. constexpr _iterator(const _iterator& iter) = default;
  194. constexpr _iterator(_iterator&& iter) = default;
  195. constexpr ~_iterator() = default;
  196. constexpr _iterator& operator=(const _iterator& iter) = default;
  197. constexpr _iterator& operator=(_iterator&& iter) = default;
  198. constexpr bool operator==(const _iterator& iter) const = default;
  199. constexpr reference operator*(void) const { return p->value; }
  200. constexpr pointer operator&(void) const { return std::addressof(p->value); }
  201. constexpr pointer operator->(void) const { return this->operator&(); }
  202. constexpr _iterator& operator++(void)
  203. { p = p->next(); return *this; }
  204. constexpr _iterator operator++(int)
  205. { _iterator ret(p); (void)this->operator++(); return ret; }
  206. constexpr _iterator& operator--(void)
  207. { p = p->prev(); return *this; }
  208. constexpr _iterator operator--(int)
  209. { _iterator ret(p); (void)this->operator--(); return ret; }
  210. constexpr operator bool() const
  211. { return p; }
  212. constexpr operator _iterator<true>() const
  213. { return _iterator<true> { p }; }
  214. };
  215. using iterator = _iterator<false>;
  216. using const_iterator = _iterator<true>;
  217. using node_allocator = typename
  218. std::allocator_traits<Allocator>::template rebind_alloc<node>;
  219. using node_alloc_traits = std::allocator_traits<node_allocator>;
  220. compressed_pair<node*, node_allocator> root_data;
  221. compressed_pair<std::size_t, Compare> size_data;
  222. private:
  223. constexpr node*& _root() noexcept { return root_data.first(); }
  224. constexpr node* const& _root() const noexcept { return root_data.first(); }
  225. constexpr std::size_t& _size() noexcept { return size_data.first(); }
  226. constexpr const std::size_t& _size() const noexcept { return size_data.first(); }
  227. constexpr node_allocator& _alloc() noexcept { return root_data.second(); }
  228. constexpr const node_allocator& _alloc() const noexcept { return root_data.second(); }
  229. constexpr Compare& _comp() noexcept { return size_data.second(); }
  230. constexpr const Compare& _comp() const noexcept { return size_data.second(); }
  231. template <typename... Args>
  232. constexpr node* newnode(Args&&... key)
  233. {
  234. node* ptr = node_alloc_traits::allocate(_alloc(), 1);
  235. node_alloc_traits::construct(_alloc(), ptr, std::forward<Args>(key)...);
  236. return ptr;
  237. }
  238. constexpr void delnode(node* nd)
  239. {
  240. node_alloc_traits::destroy(_alloc(), nd);
  241. node_alloc_traits::deallocate(_alloc(), nd, 1);
  242. }
  243. constexpr void do_insertion(node* parent,
  244. node*& child_inserted, node* nd)
  245. {
  246. nd->parent = parent;
  247. child_inserted = nd;
  248. this->balance(nd);
  249. ++_size();
  250. }
  251. public:
  252. constexpr iterator end(void) noexcept
  253. { return iterator(nullptr); }
  254. constexpr const_iterator end(void) const noexcept
  255. { return const_iterator(nullptr); }
  256. constexpr const_iterator cend(void) const noexcept
  257. { return const_iterator(nullptr); }
  258. constexpr iterator begin(void) noexcept
  259. { return _root() ? iterator(_root()->leftmost()) : end(); }
  260. constexpr const_iterator begin(void) const noexcept
  261. { return _root() ? const_iterator(_root()->leftmost()) : end(); }
  262. constexpr const_iterator cbegin(void) const noexcept
  263. { return _root() ? const_iterator(_root()->leftmost()) : end(); }
  264. constexpr void destroy(node* nd)
  265. {
  266. if (!nd)
  267. return;
  268. destroy(nd->left);
  269. destroy(nd->right);
  270. delnode(nd);
  271. }
  272. constexpr void destroy() { destroy(_root()); _root() = nullptr; _size() = 0; }
  273. constexpr node* copy(node* nd)
  274. {
  275. if (!nd)
  276. return nullptr;
  277. node* newnd = newnode(nd->value);
  278. newnd->color = nd->color;
  279. ++_size();
  280. newnd->left = copy(nd->left);
  281. if (newnd->left)
  282. newnd->left->parent = newnd;
  283. newnd->right = copy(nd->right);
  284. if (newnd->right)
  285. newnd->right->parent = newnd;
  286. return newnd;
  287. }
  288. explicit constexpr rbtree(const Compare& comp, const node_allocator& alloc)
  289. : root_data{nullptr, alloc}, size_data{0, comp} { }
  290. constexpr rbtree(const rbtree& other)
  291. : rbtree(other._comp(), other._alloc())
  292. {
  293. _root() = copy(other._root());
  294. if (_root())
  295. _root()->parent = nullptr;
  296. }
  297. constexpr rbtree(const rbtree& other, const node_allocator& alloc)
  298. : rbtree(other._comp(), alloc)
  299. {
  300. _root() = copy(other._root());
  301. if (_root())
  302. _root()->parent = nullptr;
  303. }
  304. constexpr rbtree(rbtree&& other) noexcept
  305. : root_data{std::exchange(other._root(), nullptr), std::move(other._alloc())}
  306. , size_data{std::exchange(other._size(), 0), std::move(other._comp())} { }
  307. constexpr rbtree(rbtree&& other, const node_allocator& alloc) noexcept
  308. : root_data{std::exchange(other._root(), nullptr), alloc}
  309. , size_data{std::exchange(other._size(), 0), std::move(other._comp())} { }
  310. constexpr ~rbtree() { destroy(); }
  311. constexpr rbtree& operator=(const rbtree& other)
  312. {
  313. destroy(_root());
  314. _comp() = other._comp();
  315. if constexpr (node_alloc_traits::
  316. propagate_on_container_copy_assignment::value)
  317. _alloc() = other._alloc();
  318. _root() = copy(other._root());
  319. if (_root())
  320. _root()->parent = nullptr;
  321. return *this;
  322. }
  323. constexpr rbtree& operator=(rbtree&& other) noexcept
  324. {
  325. destroy(_root());
  326. _root() = std::exchange(other._root(), nullptr);
  327. _size() = std::exchange(other._size(), 0);
  328. _comp() = std::move(other._comp());
  329. if constexpr (node_alloc_traits::
  330. propagate_on_container_move_assignment::value)
  331. _alloc() = std::move(other._alloc());
  332. return *this;
  333. }
  334. constexpr void rotateleft(node* rt)
  335. {
  336. node* nrt = rt->right;
  337. if (!rt->is_root()) {
  338. if (rt->is_left_child())
  339. rt->parent->left = nrt;
  340. else
  341. rt->parent->right = nrt;
  342. } else {
  343. _root() = nrt;
  344. }
  345. nrt->parent = rt->parent;
  346. rt->parent = nrt;
  347. rt->right = nrt->left;
  348. if (rt->right)
  349. rt->right->parent = rt;
  350. nrt->left = rt;
  351. }
  352. constexpr void rotateright(node* rt)
  353. {
  354. node* nrt = rt->left;
  355. if (!rt->is_root()) {
  356. if (rt->is_left_child())
  357. rt->parent->left = nrt;
  358. else
  359. rt->parent->right = nrt;
  360. } else {
  361. _root() = nrt;
  362. }
  363. nrt->parent = rt->parent;
  364. rt->parent = nrt;
  365. rt->left = nrt->right;
  366. if (rt->left)
  367. rt->left->parent = rt;
  368. nrt->right = rt;
  369. }
  370. constexpr void balance(node* nd)
  371. {
  372. if (nd->is_root()) {
  373. nd->toblack();
  374. return;
  375. }
  376. if (node::is_black(nd->parent))
  377. return;
  378. node* p = nd->parent;
  379. node* pp = nd->grandparent();
  380. node* uncle = nd->uncle();
  381. if (node::is_red(uncle)) {
  382. p->toblack();
  383. uncle->toblack();
  384. pp->tored();
  385. this->balance(pp);
  386. return;
  387. }
  388. if (p->is_left_child()) {
  389. if (nd->is_left_child()) {
  390. p->toblack();
  391. pp->tored();
  392. this->rotateright(pp);
  393. } else {
  394. this->rotateleft(p);
  395. this->balance(p);
  396. }
  397. } else {
  398. if (nd->is_right_child()) {
  399. p->toblack();
  400. pp->tored();
  401. this->rotateleft(pp);
  402. } else {
  403. this->rotateright(p);
  404. this->balance(p);
  405. }
  406. }
  407. }
  408. template <typename U>
  409. constexpr node* _find(const U& key) const
  410. {
  411. for (node* cur = _root(); cur; ) {
  412. if (_comp()(key, cur->value))
  413. cur = cur->left;
  414. else if (_comp()(cur->value, key))
  415. cur = cur->right;
  416. else
  417. return cur;
  418. }
  419. return nullptr;
  420. }
  421. template <typename U>
  422. constexpr iterator find(const U& key) const
  423. { return iterator { _find(key) }; }
  424. // RBTREE RECURSIVE DELETE
  425. // THIS FUNCTION DOES NOT DELLOCATE THE NODE
  426. // CALLER IS RESPONSIBLE FOR FREEING THE MEMORY
  427. // @param: nd is guaranteed to be a leaf node
  428. constexpr void _erase(node* nd)
  429. {
  430. if (nd->is_root())
  431. return;
  432. if (node::is_black(nd)) {
  433. node* p = nd->parent;
  434. node* s = nullptr;
  435. if (nd->is_left_child())
  436. s = p->right;
  437. else
  438. s = p->left;
  439. if (node::is_red(s)) {
  440. p->tored();
  441. s->toblack();
  442. if (nd->is_right_child()) {
  443. this->rotateright(p);
  444. s = p->left;
  445. } else {
  446. this->rotateleft(p);
  447. s = p->right;
  448. }
  449. }
  450. node* r = nullptr;
  451. if (node::is_red(s->left)) {
  452. r = s->left;
  453. if (s->is_left_child()) {
  454. r->toblack();
  455. s->color = p->color;
  456. this->rotateright(p);
  457. p->toblack();
  458. } else {
  459. r->color = p->color;
  460. this->rotateright(s);
  461. this->rotateleft(p);
  462. p->toblack();
  463. }
  464. } else if (node::is_red(s->right)) {
  465. r = s->right;
  466. if (s->is_left_child()) {
  467. r->color = p->color;
  468. this->rotateleft(s);
  469. this->rotateright(p);
  470. p->toblack();
  471. } else {
  472. r->toblack();
  473. s->color = p->color;
  474. this->rotateleft(p);
  475. p->toblack();
  476. }
  477. } else {
  478. s->tored();
  479. if (node::is_black(p))
  480. this->_erase(p);
  481. else
  482. p->toblack();
  483. }
  484. }
  485. }
  486. // delete nd from the tree. make nd safe to deallocate
  487. // THIS FUNCTION DOES NOT DELLOCATE THE NODE
  488. // CALLER IS RESPONSIBLE FOR FREEING THE MEMORY
  489. constexpr node* erase(node* nd)
  490. {
  491. if (nd->is_root() && nd->is_leaf()) {
  492. _root() = nullptr;
  493. return nullptr;
  494. }
  495. node* next = nd->next();
  496. while (!nd->is_leaf()) {
  497. node* alt = nd->right ? nd->right->leftmost() : nd->left;
  498. if (nd->is_root())
  499. _root() = alt;
  500. node::swap(nd, alt);
  501. }
  502. this->_erase(nd);
  503. if (nd->is_left_child())
  504. nd->parent->left = nullptr;
  505. else
  506. nd->parent->right = nullptr;
  507. return next;
  508. }
  509. constexpr iterator erase(iterator pos) noexcept
  510. {
  511. node* nextpos = erase(pos.p);
  512. delnode(pos.p);
  513. --_size();
  514. return iterator { nextpos };
  515. }
  516. constexpr iterator erase(const_iterator pos) noexcept
  517. {
  518. node* nextpos = erase(pos.p);
  519. delnode(pos.p);
  520. --_size();
  521. return iterator { nextpos };
  522. }
  523. template <typename U>
  524. constexpr iterator lower_bound(U&& val) const
  525. {
  526. node* cur = _root();
  527. node* result = nullptr;
  528. while (cur) {
  529. if (!_comp()(cur->value, val)) {
  530. result = cur;
  531. cur = cur->left;
  532. }
  533. else {
  534. cur = cur->right;
  535. }
  536. }
  537. return iterator { result };
  538. }
  539. template <typename U>
  540. constexpr iterator upper_bound(U&& val) const
  541. {
  542. iterator iter = lower_bound(std::forward<U>(val));
  543. if (iter && !_comp()(*iter, val) && !_comp()(val, *iter))
  544. return ++iter;
  545. return iter;
  546. }
  547. // value in nd MUST NOT exist in the rbtree,
  548. // that is, if a < b, then a > b
  549. constexpr void insert(node* nd)
  550. {
  551. node* cur = _root();
  552. while (cur) {
  553. if (_comp()(nd->value, cur->value)) {
  554. if (!cur->left) {
  555. do_insertion(cur, cur->left, nd);
  556. return;
  557. }
  558. cur = cur->left;
  559. } else {
  560. if (!cur->right) {
  561. do_insertion(cur, cur->right, nd);
  562. return;
  563. }
  564. cur = cur->right;
  565. }
  566. }
  567. do_insertion(cur, _root(), nd);
  568. }
  569. template <typename U>
  570. constexpr std::pair<iterator, bool> insert(U&& value)
  571. {
  572. auto iter = find(value);
  573. if (iter)
  574. return { iter, false };
  575. node* ptr = newnode(std::forward<U>(value));
  576. insert(ptr);
  577. return { iterator { ptr }, true };
  578. }
  579. template <typename... Args>
  580. constexpr std::pair<iterator, bool> emplace(Args&&... args)
  581. {
  582. node* nd = newnode(std::forward<Args>(args)...);
  583. node* exist_nd = _find(nd->value);
  584. if (exist_nd) {
  585. delnode(nd);
  586. return { iterator { exist_nd }, false };
  587. }
  588. insert(nd);
  589. return { iterator { nd }, true };
  590. }
  591. constexpr bool empty() const noexcept { return !_root(); }
  592. constexpr std::size_t size() const noexcept { return _size(); }
  593. constexpr void swap(rbtree& other)
  594. {
  595. std::swap(_root(), other._root());
  596. std::swap(_size(), other._size());
  597. std::swap(_comp(), other._comp());
  598. if constexpr (node_alloc_traits::propagate_on_container_swap::value)
  599. std::swap(_alloc(), other._alloc());
  600. }
  601. };
  602. } // namespace std::impl
  603. #endif