Policy based data structures (PBDS)

Implement set with the ability to know index of item  --> data structure order statistics tree, (unfortunately only available for the GNU C++)

g++ compiler supports some data structures that are not part of standard C++ library
---> such structures are called policy-based data structures

#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
using namespace __gnu_pbds;
template< typename Key, // Key type
	  typename Mapped, // Mapped-policy --> USE null_type for sets (bcz no mapping)
	  typename Cmp_Fn = less<Key>, // Key comparison functor
	  typename Tag = rb_tree_tag, // Specifies which underlying data structure to use
	  class Node_Update = null_node_update, // A policy for updating node invariants >
Node_Update — class denotes policy for updating node invariants. By default, set to null_node_update, i.e, additional info not stored in the vertices. In addition, C++ implemented an update policy tree_order_statistics_node_update => WE USE this

This gives the same benefit as set with two extra features :-   
pbds.find_by_order(k) => returns iterator to the k-th index like array --> from zero order_of_key(7) => return number of items in set that are strictly smaller than 7
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;
  • If use greater<int> --> everything is sorted in reversed order
  • If use less_equal<int> --> behaves similar to multiset --> BUT pbds is to store elements in strict ordering => less_equal can cause undefined behavior
    • Instead use pair<int, int> --> SEE below
typedef tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
  • Search - pbds.upper_bound({value, -1})
  • Insert - pbds.insert({value, pbds.size()})
    • Note that the second value of the insertion has to be unique => use size()
  • Delete - pbds.erase(pbds.upper_bound({value, -1}))

Comments

Popular posts from this blog

Graphs

Basics

Hashing