using
System;
class
GFG
{
static
readonly
int
N = 4;
public
class
Query
{
public
int
x1, y1;
public
int
x2, y2;
public
Query(
int
x1,
int
y1,
int
x2,
int
y2)
{
this
.x1 = x1;
this
.y1 = y1;
this
.x2 = x2;
this
.y2 = y2;
}
};
static
void
updateBIT(
int
[,]BIT,
int
x,
int
y,
int
val)
{
for
(; x <= N; x += (x & -x))
{
for
(; y <= N; y += (y & -y))
BIT[x,y] += val;
}
return
;
}
static
int
getSum(
int
[,]BIT,
int
x,
int
y)
{
int
sum = 0;
for
(; x > 0; x -= x&-x)
{
for
(; y > 0; y -= y&-y)
{
sum += BIT[x, y];
}
}
return
sum;
}
static
void
constructAux(
int
[,]mat,
int
[,]aux)
{
for
(
int
i = 0; i <= N; i++)
for
(
int
j = 0; j <= N; j++)
aux[i, j] = 0;
for
(
int
j = 1; j <= N; j++)
for
(
int
i = 1; i <= N; i++)
aux[i, j] = mat[N - j, i - 1];
return
;
}
static
void
construct2DBIT(
int
[,]mat,
int
[,]BIT)
{
int
[,]aux =
new
int
[N + 1, N + 1];
constructAux(mat, aux);
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++)
{
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);
updateBIT(BIT, i, j, aux[i,j] -
(v1 - v2 - v4 + v3));
}
}
return
;
}
static
void
answerQueries(Query []q,
int
m,
int
[,]BIT)
{
for
(
int
i = 0; i < m; i++)
{
int
x1 = q[i].x1 + 1;
int
y1 = q[i].y1 + 1;
int
x2 = q[i].x2 + 1;
int
y2 = q[i].y2 + 1;
int
ans = getSum(BIT, x2, y2) -
getSum(BIT, x2, y1 - 1) -
getSum(BIT, x1 - 1, y2) +
getSum(BIT, x1 - 1, y1 - 1);
Console.Write(
"Query({0}, {1}, {2}, {3}) = {4}\n"
,
q[i].x1, q[i].y1, q[i].x2, q[i].y2, ans);
}
return
;
}
public
static
void
Main(String[] args)
{
int
[,]mat = { {1, 2, 3, 4},
{5, 3, 8, 1},
{4, 6, 7, 5},
{2, 4, 8, 9} };
int
[,]BIT =
new
int
[N + 1,N + 1];
construct2DBIT(mat, BIT);
Query []q = {
new
Query(1, 1, 3, 2),
new
Query(2, 3, 3, 3),
new
Query(1, 1, 1, 1)};
int
m = q.Length;
answerQueries(q, m, BIT);
}
}