有人可以给我提供二维二元索引树的算法吗?

can someone provide me the algorithm of 2-d binary indexed tree?

本文关键字:二元 索引 算法 二维      更新时间:2023-10-16

我在互联网上搜索,但找不到好的。 我从 geeksforgeeks.org 那里得到了一些帮助,但无法理解我们在更新 BIT 数组时从 aux[i][j] 中减去 v1-v2-v2-v4+v3 的构造部分。只要让我知道我们为什么要在这里减去。

void constructAux(int mat[][N], int aux[][N+1])
{
// Initialise Auxiliary array to 0
for (int i=0; i<=N; i++)
for (int j=0; j<=N; j++)
aux[i][j] = 0;
// Construct the Auxiliary Matrix
for (int j=1; j<=N; j++)
for (int i=1; i<=N; i++)
aux[i][j] = mat[N-j][i-1];
return;
}
// A function to construct a 2D BIT
void construct2DBIT(int mat[][N], int BIT[][N+1])
{
// Create an auxiliary matrix
int aux[N+1][N+1];
constructAux(mat, aux);
// Initialise the BIT to 0
for (int i=1; i<=N; i++)
for (int j=1; j<=N; j++)
BIT[i][j] = 0;
for (int j=1; j<=N; j++)
{
for (int i=1; i<=N; i++)
{
// Creating a 2D-BIT using update function
// everytime we/ encounter a value in the
// input 2D-array
int v1 = getSum(BIT, i, j);
int v2 = getSum(BIT, i, j-1);
int v3 = getSum(BIT, i-1, j-1);
int v4 = getSum(BIT, i-1, j);
// Assigning a value to a particular element
// of 2D BIT
updateBIT(BIT, i, j, aux[i][j]-(v1-v2-v4+v3));
}
}
return;
}

在topcoder上有一个很好的解释2d二元索引树。

要了解aux[i][j]-(v1-v2-v4+v3)请注意:

  1. getSum(BIT,i,j)返回矩形中所有元素的总和,左上角位于原点,右下角位于坐标 i,j。
  2. 因此getSum(BIT, i, j)-getSum(BIT, i, j-1)是第 j 行中所有元素的总和,直到第 I 列
  3. 因此getSum(BIT, i-1, j)-getSum(BIT, i-1, j-1)是第 j 行中所有元素的总和,直到第 I-1 列
  4. 因此v1-v2-v4+v3是位置 I,j 的入场值

更新代码通过在位置添加值来工作。 在此代码中,他们希望将值设置为aux[i][j]中的特定选项,因此执行此操作的方法是将目标值和当前值之间的差异相加。

(话虽如此,这段代码会依次更新每个值,所以你应该发现 v1-v2-v4+v3 总是等于零,因为每个值都开始清除(