Shubham
Shubham
◼Background
◼Problem Statement
◼Motivation
◼Prefix Sum
◼Upadation
◼References
Problem Statement
Binary Indexed Tree data structure, also with the worst time
complexity O(m log n) — but Binary Indexed Trees are
easier to code and require less memory space than RMQ.
Binary Representation
Removing bits from mask
mask = think in integer bits
Assume we have numbers X, Y
If for every position in Y with 1 AND X has 1
X = 10010100
Y = 00010100
X - Y removes all Y 1s from X
Another longer/general way to do so:
X & ~Y
10010100 &
11101011 =
10000000
Least/Most Significant Bit
Src: http://www.electronique-et-informatique.fr/Digit/images/MSBLSB.gif
Src: http://tronixstuff.com/wp-content/uploads/2011/05/binnum.jpg
Two’s Complement Representation
+20 = 00010100
-20 = 11101100
20 & -20 = 00000100
Get it...subtract it
index - (index & -index)
00010100 - 00000100 = 00010000
Integer as sums of powers of 2
= 010010011
Src: http://images.slideplayer.com/5/1546412/slides/slide_22.jpg
Our problem
Let’s move to our problem
Given an array of integer N
Assume index 0 always will be 0 (NOT in use)
2 query types:
Add value val to position index
Sum values from 1 to index
xx 3 2 -1 6 5 4 -3 3 7 2 3
xx 3 2 4 6 5 4 -3 3 7 2 3
Sum(1,147) =
Sum(147,147) + Sum(146,145) + Sum(144,129) + Sum(128,1)
147 ⇒ positions {147, 146, 144, 128} with ranges {1, 2, 16,
128}
Motivation
Notice: 8 = 1000 => has 3 trailing zeros. Try to replace each 0 with 1
1001 = 9
1010 = 10
1100 = 12
# of trailing zeros = # children … child remove last bit => go to parent
Get Interval Accumulation
Sum(15) = BIT(15) + BIT(14) + BIT(12) + BIT(8)
= 1111 ⇒ 1110 ⇒ 1100 ⇒ 1000 ⇒ 0 = STOP
▪ 0001000 ⇒ r = 3 ⇒ 2^3 = 8
▪ 0101000
▪ 1101000
▪ 1111000
▪ 1001000
◼ So our focus on “last bit”, NOT before that
Updating position
▪ “last bit” at k = 0
▪ We need enumeration includes whole 11
▪ So parent need to be a 1 before these 11
▪ E.g. ⇒ 0100
◼ So general rule
▪ 100100001000 100100011100
▪ 100100010000 100100100000
Notice: 8 = 1000 => has 3 trailing zeros. Remove last bit, and add 1, 2, 3...trailing ones
0100 = 4
0110 = 6
0111 = 7
# of trailing zeros = # children
Updating tree