Advertisement
Kaidul

Segment Tree Alternatives for static array

Apr 13th, 2013
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. #define INF 1 << 30
  8. #define Max 100
  9.  
  10. int data[] = {21, 2, 7, 3, 4, 5, 1, 6, 9, 32, 11, 13, 23, 17, 8};
  11. const size_t arrLength = sizeof data / sizeof(data[0]);
  12.  
  13.  
  14. /*  Top Down Approach  */
  15. int cache[Max][Max];
  16.  
  17. int RMQ(int begin, int end) {
  18.     if(cache[begin][end] != -1) return cache[begin][end];
  19.     if(begin == end) return cache[begin][end] = begin;
  20.     if(begin > end) return -1;
  21.     return cache[begin][end] = (data[RMQ(begin, end - 1)] < data[end]) ? RMQ(begin, end - 1) : end;
  22. }
  23.  
  24.  
  25. /*  Bottom up Approach  */
  26. int dp[Max][Max];
  27.  
  28. void RMQ() {
  29.     memset(dp, -1, sizeof dp);
  30.     for(int i = 0; i < arrLength; i++) {
  31.         for (int j = i; j < arrLength; j++) {
  32.             if(i == j) dp[i][j] = i;
  33.             else dp[i][j] = (data[dp[i][j - 1]] < data[j]) ? dp[i][j - 1] : j;
  34.         }
  35.     }
  36. }
  37.  
  38. void update(int index, int item) {
  39.     data[index] = item;
  40. }
  41.  
  42. int main() {
  43.     memset(cache, -1, sizeof cache);
  44.     cout << RMQ(0, 8) << "\n";
  45.  
  46.     RMQ();
  47.     cout << dp[0][8] << "\n";
  48.  
  49.     update(6, 100);
  50.     RMQ();
  51.     cout << dp[0][8];
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement