Advertisement
manish

Sparse Table

Oct 26th, 2019
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.72 KB | None | 0 0
  1. from math import log2
  2.  
  3.  
  4. class Sparse:
  5.     def __init__(self, a):
  6.         self.a = a
  7.         self.n = len(a)
  8.         self.k = int(log2(self.n)) + 1
  9.         self.lookup = [[0]*self.k for x in range(self.n)]
  10.         self.process()
  11.  
  12.     def process(self):
  13.         for i in range(self.n):
  14.             self.lookup[i][0] = self.a[i]
  15.         j = 1
  16.         while (1 << j) <= self.n:
  17.             i = 0
  18.             while (i + (1 << j) - 1) < self.n:
  19.                 self.lookup[i][j] = min(self.lookup[i][j-1], self.lookup[i + (1 << (j - 1))][j - 1])
  20.                 i += 1
  21.             j += 1
  22.  
  23.     def query(self, a, b):
  24.         x = int(log2(b - a + 1))
  25.         return min(self.lookup[a][x], self.lookup[b - (1 << x) + 1][x])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement