Advertisement
STANAANDREY

indexed set

Jun 16th, 2024 (edited)
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include <ext/pb_ds/assoc_container.hpp>
  3.  
  4. using namespace std;
  5. using namespace __gnu_pbds;
  6.  
  7. // Define the indexed_set using a tree structure with order statistics
  8. using isType = int;
  9. typedef tree<isType, null_type, less<isType>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;
  10.  
  11. int main() {
  12.     // Create an indexed_set
  13.     indexed_set s;
  14.  
  15.     // Insert elements into the indexed_set
  16.     s.insert(5);
  17.     s.insert(1);
  18.     s.insert(10);
  19.     s.insert(3);
  20.  
  21.     // Print the elements in the indexed_set (they are stored in sorted order)
  22.     cout << "Elements in the set: ";
  23.     for (auto x : s)
  24.         cout << x << " "; // Output: 1 3 5 10
  25.     cout << endl;
  26.  
  27.     // Find the k-th smallest element (0-indexed)
  28.     cout << "1st smallest element: " << *s.find_by_order(0) << endl; // Output: 1
  29.     cout << "2nd smallest element: " << *s.find_by_order(1) << endl; // Output: 3
  30.     cout << "3rd smallest element: " << *s.find_by_order(2) << endl; // Output: 5
  31.  
  32.     // Find the number of elements strictly less than a given value
  33.     cout << "Number of elements less than 5: " << s.order_of_key(5) << endl; // Output: 2
  34.     cout << "Number of elements less than 6: " << s.order_of_key(6) << endl; // Output: 3
  35.  
  36.     // Erase an element
  37.     s.erase(3);
  38.     cout << "After erasing 3, elements in the set: ";
  39.     for (auto x : s)
  40.         cout << x << " "; // Output: 1 5 10
  41.     cout << endl;
  42.  
  43.     return 0;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement