class
Compressed2DBIT:
def
__init__(
self
, n, m):
self
.n
=
n
self
.m
=
m
self
.bit
=
[[
0
]
*
(m
+
1
)
for
_
in
range
(n
+
1
)]
self
.tree
=
None
def
update(
self
, x, y, val):
while
x <
=
self
.n:
y1
=
y
while
y1 <
=
self
.m:
self
.bit[x][y1]
+
=
val
y1
+
=
y1 &
-
y1
x
+
=
x &
-
x
def
query(
self
, x, y):
s
=
0
while
x >
0
:
y1
=
y
while
y1 >
0
:
s
+
=
self
.bit[x][y1]
y1
-
=
y1 &
-
y1
x
-
=
x &
-
x
return
s
def
compress(
self
):
self
.tree
=
[
[
0
]
*
self
.m
for
_
in
range
(
self
.n)]
for
i
in
range
(
1
,
self
.n
+
1
):
for
j
in
range
(
1
,
self
.m
+
1
):
self
.tree[i
-
1
][j
-
1
]
=
self
.query(i, j)
-
self
.query(
i
-
1
, j)
-
self
.query(i, j
-
1
)
+
self
.query(i
-
1
, j
-
1
)
self
.bit_compressed
=
None
arr
=
[[
1
,
2
,
3
,
4
,
5
],
[
6
,
7
,
8
,
9
,
10
],
[
11
,
12
,
13
,
14
,
15
],
[
16
,
17
,
18
,
19
,
20
]]
bit
=
Compressed2DBIT(
4
,
5
)
for
i
in
range
(
4
):
for
j
in
range
(
5
):
bit.update(i
+
1
, j
+
1
, arr[i][j])
print
(bit.query(
2
,
3
))
print
(bit.query(
4
,
5
))
bit.compress()
print
(bit.query(
2
,
3
))
print
(bit.query(
4
,
5
))
print
(bit.tree)
Stay connected with us on social media platform for instant update click here to join our Twitter, & Facebook We are now on Telegram. Click here to join our channel (@TechiUpdate) and stay updated with the latest Technology headlines. For all the latest Technology News Click Here