-
Notifications
You must be signed in to change notification settings - Fork 0
/
Range sum query using Sparse Table
66 lines (50 loc) · 1.48 KB
/
Range sum query using Sparse Table
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""We have an array arr[]. We need to find the sum of all the elements in the range L and R where 0 <= L <= R <= n-1. Consider a situation when there are many range queries.
Examples:
Input : 3 7 2 5 8 9
query(0, 5)
query(3, 5)
query(2, 4)
Output : 34
22
15
Note : array is 0 based indexed
and queries too."""
# Python3 program to find the sum in a given
# range in an array using sparse table.
# Because 2^17 is larger than 10^5
k = 16
# Maximum value of array
n = 100000
# k + 1 because we need to access
# table[r][k]
table = [[0 for j in range(k+1)] for i in range(n)]
# it builds sparse table
def buildSparseTable(arr, n):
global table, k
for i in range(n):
table[i][0] = arr[i]
for j in range(1,k+1):
for i in range(0,n-(1<<j)+1):
table[i][j] = table[i][j-1] + \
table[i + (1 << (j - 1))][j - 1]
# Returns the sum of the elements in the range
# L and R.
def query(L, R):
global table, k
# boundaries of next query, 0 - indexed
answer = 0
for j in range(k,-1,-1):
if (L + (1 << j) - 1 <= R):
answer = answer + table[L][j]
# instead of having L ', we
# increment L directly
L+=1<<j
return answer
# Driver program
if __name__ == '__main__':
arr = [3, 7, 2, 5, 8, 9]
n = len(arr)
buildSparseTable(arr, n)
print(query(0,5))
print(query(3,5))
print(query(2,4))