Advertisement
KennasSticky

Segment Tree Java Implementation

Jul 10th, 2021
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class SegmentTree {
  4.  
  5.     static int[] arr;
  6.  
  7.     public static void main(String[] args) {
  8.         Scanner scan = new Scanner(System.in);
  9.         int n = scan.nextInt(); // length of the array
  10.         int len = (int) Math.pow(2, Math.ceil(Math.log(n)/Math.log(2))); // little math trick to get first power of 2 >= n
  11.  
  12.         arr = new int[2*len];
  13.  
  14.         // add the values through all the dependant values O ( log n )
  15.         for (int i = 0; i < len; i++) {
  16.             int a;
  17.  
  18.             // append values if length of the array is not a power of 2
  19.             if (i > n) {
  20.                 a = 0;
  21.             } else a = scan.nextInt();
  22.  
  23.             // add a value through all its parent values.
  24.             add(i + len, a);
  25.         }
  26.  
  27.         int q = scan.nextInt(); // number of queries
  28.  
  29.         while (q-- > 0) {
  30.             int a = scan.nextInt();
  31.             int b = scan.nextInt();
  32.  
  33.             System.out.println(sum(a + len, b + len));
  34.         }
  35.     }
  36.  
  37.     // Performs O(log n) addition operations to all dependant values
  38.     static void add(int k, int x) {
  39.         arr[k] += x;
  40.         for (k /= 2; k >= 1; k /= 2) {
  41.             arr[k] = arr[2 * k] + arr[2 * k + 1];
  42.         }
  43.     }
  44.  
  45.     // Performs O(log n) operations to find the highest values that correspond to a precalculated subrange
  46.     static int sum(int a, int b) {
  47.         int s = 0;
  48.         while (a <= b) {
  49.             if (a % 2 == 1) s += arr[a++];
  50.             if (b % 2 == 0) s += arr[b--];
  51.              a /= 2; b /= 2;
  52.         }
  53.         return s;
  54.     }
  55.  
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement