- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 98 lines of Python from the credited upstream file booking-concert-tickets-in-groups.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12345 678class SegmentTree(object):9 def __init__(self, N,10 build_fn=lambda _: float("inf"),11 query_fn=lambda x, y: y if x is None else x if y is None else min(x, y),12 update_fn=lambda x: x):13 self.tree = [None]*(2*2**((N-1).bit_length()))14 self.base = len(self.tree)215 self.query_fn = query_fn16 self.update_fn = update_fn17 for i in xrange(self.base, self.base+N):18 self.tree[i] = build_fn(i-self.base)19 for i in reversed(xrange(1, self.base)):20 self.tree[i] = query_fn(self.tree[2*i], self.tree[2*i+1])21 22 def update(self, i, h):23 x = self.base+i24 self.tree[x] = self.update_fn(h)25 while x > 1:26 x = 227 self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])28 29 def query(self, L, R):30 L += self.base31 R += self.base32 left = right = None33 while L <= R:34 if L & 1:35 left = self.query_fn(left, self.tree[L])36 L += 137 if R & 1 == 0:38 right = self.query_fn(self.tree[R], right)39 R -= 140 L = 241 R = 242 return self.query_fn(left, right)43 44 4546class BookMyShow(object):47 48 def __init__(self, n, m):49 """50 :type n: int51 :type m: int52 """53 self.__st = SegmentTree(n,54 build_fn=lambda _: [m]*2,55 query_fn=lambda x, y: y if x is None else x if y is None else [max(x[0], y[0]), x[1]+y[1]])56 self.__m = m57 self.__i = 058 59 def gather(self, k, maxRow):60 """61 :type k: int62 :type maxRow: int63 :rtype: List[int]64 """65 i = 166 if k > self.__st.tree[i][0]:67 return []68 while i < self.__st.base:69 i = 2*i+int(self.__st.tree[2*i][0] < k)70 if i-self.__st.base > maxRow:71 return []72 cnt = self.__st.tree[i][0]73 c = self.__m-cnt74 i -= self.__st.base75 self.__st.update(i, [cnt-k]*2)76 return [i, c]77 78 def scatter(self, k, maxRow):79 """80 :type k: int81 :type maxRow: int82 :rtype: bool83 """84 cnt = self.__st.query(self.__i, maxRow)85 if not cnt or cnt[1] < k:86 return False87 for i in xrange(self.__i, maxRow+1):88 cnt = self.__st.tree[self.__st.base+i][1]89 c = min(cnt, k)90 cnt -= c91 if not cnt:92 self.__i += 193 self.__st.update(i, [cnt]*2)94 k -= c95 if not k:96 break97 return True98