-->

Fenwick Tree Java

2019-02-28 07:25发布

问题:

I tried to implement the Fenwick Tree in Java, but I am not getting the desired result. Here is my code:

import java.io.*;
import java.util.*;
import java.math.*;

class fenwick1 {
    public static int N;
    public static long[] a;
    public static void main(String[] args)throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        a = new long[N];
        String[] str = br.readLine().split(" ");
        for (int i = 0; i < N; i++) {
            a[i] = Long.parseLong(str[i]);
        }
        increment(2, 10);
        System.out.println(a[2]);
        System.out.println(query(4));
    }

    public static void increment(int at, int by) {
        while (at < a.length) {
            a[at] += by;
            at |= (at + 1);
        }
    }

    public static int query(int at) {
        int res = 0;
        while (at >= 0) {
            res += a[at];
            at = (at & (at + 1)) - 1;
        }
        return res;
    }
}

When I give input:

10
1 2 3 4 5 6 7 8 9 10

I get:

13
19

So the increment function works fine. But query(4) should give the cumulative sum up to index 4 i.e.

(1 + 2 + 13 + 4 + 5) = 25

回答1:

You do not initialize it properly. Instead of:

for (int i = 0; i < N; i++) {
    a[i] = Long.parseLong(str[i]);
}

It should be:

for (int i = 0; i < N; i++) {
    increment(i, (int)Long.parseLong(str[i]));
}

because a[i] should store a cumulative sum, not a single element.

If you want to store the initial array elements too, you can just create one more array:

long[] initA = new long[N];
for (int i = 0; i < N; i++) {
    initA[i] = Long.parseLong(str[i]);
    increment(i, (int)initA[i]);
}