Advertisement
KennasSticky

Fenwick Tree - Java Implementation

Jul 11th, 2021
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class FenwickTree {
  4.  
  5.   static int[] arr, tree;
  6.   public static void main(String[] args) {
  7.     Scanner scan = new Scanner(System.in);
  8.  
  9.     int n = scan.nextInt();
  10.  
  11.     arr = new int[n+1];
  12.     tree = new int[n+1];
  13.  
  14.     for (int i = 1; i <= n; i++) {
  15.       arr[i] = scan.nextInt();
  16.     }
  17.  
  18.     // build the tree
  19.     for (int i = 1; i <= n; i++) {
  20.       int left = i - (i & -i) + 1;
  21.       int sum = 0;
  22.       for (int j = left; j <= i; j++) {
  23.         sum += arr[j];
  24.       }
  25.       tree[i] = sum;
  26.     }
  27.  
  28.     System.out.println(Arrays.toString(tree));
  29.   }  
  30.  
  31.   static int sum(int b) {
  32.     int sum = 0;
  33.     while (b >= 1) {
  34.       sum += tree[b];
  35.       b -= b & -b;
  36.     }
  37.     return sum;
  38.   }
  39.  
  40.   static void update(int x, int val) {
  41.     while (x <= tree.length) {
  42.       tree[x] += val;
  43.       x += x & -x;
  44.     }
  45.   }
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement