본문 바로가기

PS/Algorithms

[Java] 2-Dimentional Fenwick Tree

https://uldada.tistory.com/3

 

2차원 펜윅트리 이해하기(2-dimentional Fenwick Tree)

펜윅트리는 비트연산을 통해 빠른 시간에 구간합을 구하는 배열 형태의 트리이다. 이 글에서는 2차원 펜윅트리만을 설명하고 있다. 1차원 펜윅트리에 대한 이해가 필요하면 블로그 내 펜윅트리

uldada.tistory.com

해당 칸이 들어가는 tree 칸에 대해 전부 들어가야 하므로

각 x row에 대해 모든 y col 칸의 업데이트가 필요하다.

static void update(int x, int y, int v){
    while (x <= n){
        int temp_y = y;
        while (temp_y <= n){
            tree[x][temp_y] += v;
            temp_y += (temp_y & -temp_y);
        }
        x += (x & -x);
    }
}

static int sum(int x, int y){
    int sum = 0;
    while (x > 0){
        int temp_y = y;
        while (temp_y > 0){
            sum += tree[x][temp_y];
            temp_y -= (temp_y & -temp_y);
        }
        x -= (x & -x);
    }
    return sum;
}

 

합은 다음과 같이 구한다.

pw.println(sum(x2, y2) - sum(x1 - 1, y2) - sum(x2, y1 - 1) + sum(x1 - 1, y1 - 1));