Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. #include <cmath>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. template <class T = int>
  6. class RangeMinMaxQuery {
  7. private:
  8. T **_table;
  9. bool _maxQ;
  10. unsigned long _n;
  11. public:
  12. RangeMinMaxQuery(const unsigned long n, bool maxQuery) {
  13. this->_n = n;
  14. this->_maxQ = maxQuery;
  15. this->_table = new T*[this->_n];
  16. unsigned long limit = lrint(log2(this->_n)) + 1;
  17. for (unsigned long i = 0; i < this->_n; ++i) (this->_table)[i] = new T[limit];
  18. };
  19. RangeMinMaxQuery(const T a[], const unsigned long n, bool maxQuery) : RangeMinMaxQuery(n, maxQuery) {
  20. this->build(a);
  21. }
  22. void build(const T a[]) {
  23. for (unsigned long i = 0; i < this->_n; ++i) (this->_table)[i][0] = a[i];
  24. for (unsigned long expOf2 = 1, len; (len = (1 << expOf2)) <= this->_n; ++expOf2)
  25. for (unsigned long i = 0; i + len <= this->_n; ++i)
  26. (this->_table)[i][expOf2] = this->_maxQ?
  27. max((this->_table)[i][expOf2-1], (this->_table)[i+(1<<(expOf2-1))][expOf2-1]):
  28. min((this->_table)[i][expOf2-1], (this->_table)[i+(1<<(expOf2-1))][expOf2-1]);
  29. };
  30. // min/max query for [start; end] segment
  31. T query(const unsigned long start, const unsigned long end) {
  32. unsigned long length = end - start + 1;
  33. unsigned long expOf2 = lrint(floor(log2(length)));
  34. return this->_maxQ ? max((this->_table)[start][expOf2], (this->_table)[end-(1<<expOf2)+1][expOf2]) : min((this->_table)[start][expOf2], (this->_table)[end-(1<<expOf2)+1][expOf2]);
  35. };
  36. ~RangeMinMaxQuery() {
  37. for (unsigned long i = 0; i < this->_n; ++i) (this->_table)[i] = nullptr;
  38. this->_table = nullptr;
  39. }
  40. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement