Advertisement
dipBRUR

20

Nov 19th, 2017
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. // Algo : Sliding Range Minimum Query
  2.  
  3. int arr[mx];
  4. int N, D;
  5.  
  6. void SRMQ() {
  7. deque <int> dqMin, dqMax;
  8. for (int i=0; i<N; i++) {
  9. int num = arr[i];
  10. while (!dqMin.empty() and dqMin.front()>num)
  11. dqMin.pop_front();
  12. dqMin.push_front(num);
  13. if (i>=D and arr[i-D]==dqMin.back())
  14. dqMin.pop_back();
  15.  
  16. while (!dqMax.empty() and dqMax.front()<num)
  17. dqMax.pop_front();
  18. dqMax.push_front(num);
  19. if (i>=D and arr[i-D]==dqMax.back())
  20. dqMax.pop_back();
  21.  
  22. if (i>=D-1) {
  23. int mini = dqMin.back();
  24. int maxi = dqMax.back();
  25. cout << mini << " " << maxi << endl;
  26. }
  27. }
  28. }
  29.  
  30. // Algo : Sparse Table
  31. // Find Minimum Number in a given range
  32. // Complexity : computeST -> O(Nlog2N), query -> O(1)
  33.  
  34. int ST[24][mx], A[mx];
  35.  
  36. void computeST(int n) {
  37. for (int i=0; i<n; i++)
  38. ST[0][i] = i;
  39. for (int k=1; (1 << k) < n; k++) {
  40. for (int i=0; i+(1 << k) <= n; i++) {
  41. int x = ST[k-1][i];
  42. int y = ST[k-1][i+(1 << (k-1))];
  43. ST[k][i] = A[x] <= A[y] ? x : y;
  44. }
  45. }
  46. }
  47.  
  48. int RMQ(int i, int j) {
  49. int k = log2(j-i);
  50. int x = ST[k][i];
  51. int y = ST[k][j-(1<<k)+1];
  52. return A[x] <= A[y] ? x : y; // return index
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement