Fenwick Tree Java

落爺英雄遲暮 提交于 2019-12-02 09:09:46

问题


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]);
}


来源:https://stackoverflow.com/questions/26299990/fenwick-tree-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!