fork download
  1. //
  2. // main.cpp
  3. // Segment Tree
  4. //
  5. // Created by Himanshu on 22/08/21.
  6. //
  7.  
  8. #include <iostream>
  9. #include <math.h>
  10. using namespace std;
  11.  
  12. const int N = 6;
  13. int seg[2*N-1];
  14.  
  15. int construct (int arr[], int sb, int se, int si) {
  16. if (sb == se) {
  17. seg[si] = arr[sb];
  18. } else {
  19. int mid = (sb + se)/2;
  20. seg[si] = construct(arr, sb, mid, 2*si + 1) +
  21. construct(arr, mid+1, se, 2*si + 2);
  22. }
  23. return seg[si];
  24. }
  25.  
  26. int getSum(int sb, int se, int x, int y, int i) {
  27. if (sb > y || se < x) {
  28. return 0;
  29. } else if (sb >= x && se <= y) {
  30. return seg[i];
  31. } else {
  32. int mid = (sb+se)/2;
  33. return getSum(sb, mid, x, y, 2*i + 1) + getSum(mid+1, se, x, y, 2*i + 2);
  34. }
  35. }
  36.  
  37. int main() {
  38. int arr[] = {1, 3, 2, 7, 9, 11};
  39.  
  40. // Constructing segment tree (preprocessing)
  41. construct(arr, 0, N-1, 0);
  42.  
  43. cout<<endl;
  44. // Print minimum value in arr[qs..qe]
  45. cout<<"Sum in the range:"<<endl;
  46. cout<<"x = 0, y = 2: "<<getSum(0, N-1, 0, 2, 0)<<endl;
  47. cout<<"x = 3, y = 4: "<<getSum(0, N-1, 3, 4, 0)<<endl;
  48. cout<<"x = 2, y = 5: "<<getSum(0, N-1, 2, 5, 0)<<endl;
  49. cout<<"x = 3, y = 5: "<<getSum(0, N-1, 3, 5, 0)<<endl;
  50. cout<<"x = 0, y = 5: "<<getSum(0, N-1, 0, 5, 0)<<endl;
  51.  
  52. return 0;
  53. }
  54.  
Success #stdin #stdout 0s 5600KB
stdin
Standard input is empty
stdout
Sum in the range:
x = 0, y = 2: 6
x = 3, y = 4: 16
x = 2, y = 5: 29
x = 3, y = 5: 27
x = 0, y = 5: 33