Files
C-Plus-Plus/data_structures/treap.cpp
realstealthninja c6af943508 fix: add cstdint header to all files using fixed width integers (#2717)
* fix: add <cstdint> to subset_sum.cpp

* fix: add <cstdint> to subarray_sum.cpp

* fix: add <cstdint> to wildcard_matching.cpp

* fix: add <cstdint> to count_bit_flips.cpp

* fix: add <cstdint> to count_of_set_bits.cpp

* fix: add <cstdint> to trailing_ciphers.cpp

* fix: add <cstdint> to hamming_distance.cpp

* doc: include doc for hamming_distance

* fix: add <cstdint> to next_higher_numebr_with_same_number_of_set_bits.cpp

* fix: add <cstdint> to power_of_2.cpp

* fix: add <cstdint> to set_kth_bit.cpp

* fix: add <cstdint> to bit_manipulation/set_kth_bit.cpp

* fix: add <cstdint> to bit_manipulation/travelling_salesman_using_bit_manipulation.cpp

* fix: add <cstdint> to ciphers/base64_encoding.cpp

* fix: add <cstdint> to ciphers/hill_cipher.cpp

* fix: add <cstdint> to ciphers/uint128_t.hpp

* fix: add <cstdint> to data_structures/dsu_path_compression.cpp

* fix: add <cstdint> to data_structures/dsu_path_compression.cpp

* fix add <cstdint> to datastructures/list_array>cpp

* fix add <cstdint> to datastructures/queue_using_array.cpp

* fix: add <cstdint> to sparse_table.cpp

* fix: add <cstdint> to stack_using_list_queue.cpp

* fix: add <cstdint> to treap.cpp

* fix: add <cstdint> to graham_scan_functions.hpp

* fix: add <cstdint> to graph/**

* fix: add integral typdefs to hashing/**

* fix: add <cstdint> to math/**

* fix: add <cstdint> to numerical_methods/**

* fix: add <cstdint> to other/**

* fix: add <cstdint> to search/**

* fix: add <cstdint> to sorting/**

* fix: add <cstdint> to string/**

* doc: remove include statement from comment

* fix: make tests static

Co-authored-by: David Leal <halfpacho@gmail.com>

* fix: make tests static

Co-authored-by: David Leal <halfpacho@gmail.com>

* chore: use iwyu on backtracking/**.cpp

* chore: use iwyu on bit_manip/**.cpp

* chore: use iwyu on ciphers/**.cpp

* chore: use iwyu on cpu_scheduling_algorithms/**.cpp

* chore: use iwyu on data_structures/**.cpp

* chore: use iwyu on divide_and_conquer/**.cpp

* chore: use iwyu on geometry/**.cpp

* chore: use iwyu on graph/**.cpp

* chore: use iwyu on hashing/**.cpp

* chore: use iwyu on machine_learning/**.cpp

* chore: use iwyu on math/**.cpp

* chore: use iwyu on numerical_methods/**.cpp

* chore: use iwyu on others/**.cpp

* chore: use iwyu on probablity/**.cpp

* chore: use iwyu on search/**.cpp

* chore: use iwyu on sorting/**.cpp

* chore: use iwyu on strings/**.cpp

* Revert "chore: use iwyu on strings/**.cpp"

This reverts commit f2127456a8.

* Revert "chore: use iwyu on sorting/**.cpp"

This reverts commit a290ae7ee2.

* Revert "chore: use iwyu on search/**.cpp"

This reverts commit 19d136ae0f.

* Revert "chore: use iwyu on probablity/**.cpp"

This reverts commit 5dd7f82a34.

* Revert "chore: use iwyu on others/**.cpp"

This reverts commit 8a8fd42383.

* Revert "chore: use iwyu on numerical_methods/**.cpp"

This reverts commit eff2f44a50.

* Revert "chore: use iwyu on math/**.cpp"

This reverts commit c47117ca3f.

* Revert "chore: use iwyu on machine_learning/**.cpp"

This reverts commit c3897d3763.

* Revert "chore: use iwyu on hashing/**.cpp"

This reverts commit 0c6611a835.

* Revert "chore: use iwyu on graph/**.cpp"

This reverts commit dabd6d2591.

* Revert "chore: use iwyu on geometry/**.cpp"

This reverts commit 740bd65932.

* Revert "chore: use iwyu on divide_and_conquer/**.cpp"

This reverts commit 16ee49e086.

* Revert "chore: use iwyu on data_structures/**.cpp"

This reverts commit a3b719e368.

* Revert "chore: use iwyu on cpu_scheduling_algorithms/**.cpp"

This reverts commit 24e597f7e2.

* Revert "chore: use iwyu on ciphers/**.cpp"

This reverts commit 3d80295883.

* Revert "chore: use iwyu on bit_manip/**.cpp"

This reverts commit 7edcb6e458.

* Revert "chore: use iwyu on backtracking/**.cpp"

This reverts commit f0a30d7cdb.

* Update search/binary_search.cpp

* Update backtracking/subarray_sum.cpp

* Update backtracking/subset_sum.cpp

* Update backtracking/wildcard_matching.cpp

* Update bit_manipulation/count_bits_flip.cpp

* Update bit_manipulation/count_of_set_bits.cpp

* Update bit_manipulation/count_of_trailing_ciphers_in_factorial_n.cpp

* Update bit_manipulation/hamming_distance.cpp

* Update bit_manipulation/next_higher_number_with_same_number_of_set_bits.cpp

* Update bit_manipulation/power_of_2.cpp

* Update others/lru_cache.cpp

* Update bit_manipulation/set_kth_bit.cpp

* Update bit_manipulation/travelling_salesman_using_bit_manipulation.cpp

* Update ciphers/base64_encoding.cpp

* Update ciphers/hill_cipher.cpp

* Update ciphers/uint128_t.hpp

* Update cpu_scheduling_algorithms/fcfs_scheduling.cpp

* Update data_structures/dsu_path_compression.cpp

* Update data_structures/dsu_union_rank.cpp

* Update data_structures/list_array.cpp

* Update data_structures/queue_using_array.cpp

* Update data_structures/sparse_table.cpp

* Update data_structures/stack_using_queue.cpp

* Update data_structures/treap.cpp

* Update geometry/graham_scan_functions.hpp

* Update graph/bidirectional_dijkstra.cpp

* Update graph/connected_components_with_dsu.cpp

* Update graph/cycle_check_directed_graph.cpp

* Update graph/is_graph_bipartite2.cpp

* Update graph/travelling_salesman_problem.cpp

* Update hashing/md5.cpp

* Update hashing/sha1.cpp

* Update math/n_choose_r.cpp

* Update strings/z_function.cpp

* Update strings/manacher_algorithm.cpp

* Update sorting/wiggle_sort.cpp

* Update sorting/selection_sort_recursive.cpp

* Update sorting/selection_sort_iterative.cpp

* Update sorting/recursive_bubble_sort.cpp

* Update sorting/radix_sort2.cpp

* Update sorting/dnf_sort.cpp

* Update sorting/cycle_sort.cpp

* Update search/sublist_search.cpp

* Update search/saddleback_search.cpp

* Update search/interpolation_search.cpp

* Update search/floyd_cycle_detection_algo.cpp

* Update search/exponential_search.cpp

* Update search/exponential_search.cpp

* Update math/n_bonacci.cpp

* Update math/aliquot_sum.cpp

* Update math/check_factorial.cpp

* Update math/double_factorial.cpp

* Update math/eulers_totient_function.cpp

* Update math/factorial.cpp

* Update math/fibonacci.cpp

* Update math/fibonacci_matrix_exponentiation.cpp

* Update math/fibonacci_sum.cpp

* Update math/finding_number_of_digits_in_a_number.cpp

* chore: remove "/// for integral typedefs"

* chore: remove for integral typedefs from modular division

* fix: remove comment from include

* fix: add cstdint to gale shapely

---------

Co-authored-by: David Leal <halfpacho@gmail.com>
2024-11-04 17:38:54 +05:30

259 lines
7.7 KiB
C++

/**
* @file
* @brief A balanced binary search tree (BST) on the basis of binary search tree
* and heap: the [Treap](https://en.wikipedia.org/wiki/Treap) algorithm
* implementation
*
* @details
* Implementation of the treap data structre
*
* Support operations including insert, erase, and query (the rank of specified
* element or the element ranked x) as the same as BST
*
* But these operations take O(log N) time, since treap keeps property of heap
* using rotate operation, and the desired depth of the tree is O(log N).
* There's very little chance that it will degenerate into a chain like BST
*
* @author [Kairao ZHENG](https://github.com/fgmn)
*/
#include <array> /// For array
#include <cassert> /// For assert
#include <cstdint>
#include <iostream> /// For IO operations
/**
* @namespace
* @brief Data Structures
*/
namespace data_structures {
/**
* @namespace
* @brief Functions for the [Treap](https://en.wikipedia.org/wiki/Treap)
* algorithm implementation
*/
namespace treap {
const int maxNode = 1e5 + 5; ///< maximum number of nodes
/**
* @brief Struct representation of the treap
*/
struct Treap {
int root = 0; ///< root of the treap
int treapCnt = 0; ///< Total number of current nodes in the treap
std::array<int, maxNode> key = {}; ///< Node identifier
std::array<int, maxNode> priority = {}; ///< Random priority
std::array<std::array<int, 2>, maxNode> childs = {
{}}; ///< [i][0] represents the
///< left child of node i, and
///[i][1] represents the right
std::array<int, maxNode> cnt =
{}; ///< Maintains the subtree size for ranking query
std::array<int, maxNode> size = {}; ///< The number of copies per node
/**
* @brief Initialization
*/
Treap() : treapCnt(1) {
priority[0] = INT32_MAX;
size[0] = 0;
}
/**
* @brief Update the subtree size of the node
* @param x The node to update
*/
void update(int x) {
size[x] = size[childs[x][0]] + cnt[x] + size[childs[x][1]];
}
/**
* @brief Rotate without breaking the property of BST
* @param x The node to rotate
* @param t 0 represent left hand, while 1 right hand
*/
void rotate(int &x, int t) {
int y = childs[x][t];
childs[x][t] = childs[y][1 - t];
childs[y][1 - t] = x;
// The rotation will only change itself and its son nodes
update(x);
update(y);
x = y;
}
/**
* @brief Insert a value into the specified subtree (internal method)
* @param x Insert into the subtree of node x (Usually x=root)
* @param k Key to insert
*/
void _insert(int &x, int k) {
if (x) {
if (key[x] == k) {
cnt[x]++;
} // If the node already exists, the number of copies is ++
else {
int t = (key[x] < k); // Insert according to BST properties
_insert(childs[x][t], k);
// After insertion, the heap properties are retained by rotation
if (priority[childs[x][t]] < priority[x]) {
rotate(x, t);
}
}
} else { // Create a new node
x = treapCnt++;
key[x] = k;
cnt[x] = 1;
priority[x] = rand(); // Random priority
childs[x][0] = childs[x][1] = 0;
}
update(x);
}
/**
* @brief Erase a value from the specified subtree (internal method)
* @param x Erase from the subtree of node x (Usually x=root)
* @param k Key to erase
*/
void _erase(int &x, int k) {
if (key[x] == k) {
if (cnt[x] > 1) {
cnt[x]--;
} // If the node has more than one copy, the number of copies --
else {
if (childs[x][0] == 0 && childs[x][1] == 0) {
x = 0;
return;
} // If there are no children, delete and return
// Otherwise, we need to rotate the sons and delete them
// recursively
int t = (priority[childs[x][0]] > priority[childs[x][1]]);
rotate(x, t);
_erase(x, k);
}
} else { // Find the target value based on BST properties
_erase(childs[x][key[x] < k], k);
}
update(x);
}
/**
* @brief Find the KTH largest value (internal method)
* @param x Query the subtree of node x (Usually x=root)
* @param k The queried rank
* @return The element ranked number k
*/
int _get_k_th(int &x, int k) {
if (k <= size[childs[x][0]]) {
return _get_k_th(childs[x][0], k);
}
k -= size[childs[x][0]] + cnt[x];
if (k <= 0) {
return key[x];
}
return _get_k_th(childs[x][1], k);
}
/**
* @brief Query the rank of specified element (internal method)
* @param x Query the subtree of node x (Usually x=root)
* @param k The queried element
* @return The rank of element k
*/
int _get_rank(int x, int k) {
if (!x) {
return 0;
}
if (k == key[x]) {
return size[childs[x][0]] + 1;
} else if (k < key[x]) {
return _get_rank(childs[x][0], k);
} else {
return size[childs[x][0]] + cnt[x] + _get_rank(childs[x][1], k);
}
}
/**
* @brief Get the predecessor node of element k
* @param k The queried element
* @return The predecessor
*/
int get_predecessor(int k) {
int x = root, pre = -1;
while (x) {
if (key[x] < k) {
pre = key[x], x = childs[x][1];
} else {
x = childs[x][0];
}
}
return pre;
}
/**
* @brief Get the successor node of element k
* @param k The queried element
* @return The successor
*/
int get_next(int k) {
int x = root, next = -1;
while (x) {
if (key[x] > k) {
next = key[x], x = childs[x][0];
} else {
x = childs[x][1];
}
}
return next;
}
/**
* @brief Insert element (External method)
* @param k Key to insert
*/
void insert(int k) { _insert(root, k); }
/**
* @brief Erase element (External method)
* @param k Key to erase
*/
void erase(int k) { _erase(root, k); }
/**
* @brief Get the KTH largest value (External method)
* @param k The queried rank
* @return The element ranked number x
*/
int get_k_th(int k) { return _get_k_th(root, k); }
/**
* @brief Get the rank of specified element (External method)
* @param k The queried element
* @return The rank of element k
*/
int get_rank(int k) { return _get_rank(root, k); }
};
} // namespace treap
} // namespace data_structures
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
data_structures::treap::Treap mTreap; ///< Treap object instance
mTreap.insert(1);
mTreap.insert(2);
mTreap.insert(3);
assert(mTreap.get_k_th(2) == 2);
mTreap.insert(4);
mTreap.insert(5);
mTreap.insert(6);
assert(mTreap.get_next(4) == 5);
mTreap.insert(7);
assert(mTreap.get_predecessor(7) == 6);
mTreap.erase(4);
assert(mTreap.get_k_th(4) == 5);
assert(mTreap.get_rank(5) == 4);
mTreap.insert(10);
assert(mTreap.get_rank(10) == 7);
assert(mTreap.get_predecessor(10) == 7);
std::cout << "All tests have successfully passed!\n";
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}