There are 'n' coins kept on the table, numbered from 0 to 'n-1'. Initially, each coin is…
- User
There are 'n' coins kept on the table, numbered from 0 to 'n-1'. Initially, each coin is kept tails up. You have to perform two types of operations :
- Flip all coins numbered between A and B inclusive. This is represented by the command: 0 A B
- Answer how many coins numbered between A and B inclusive are heads up. This is represented by the command 1 A B Input: The first two lines contain two integers, N and Q.The first line after inputting N and Q has to be of form (1).Each of the next Q lines are of the form (2) as mentioned above. Output: Output 1 line for each of the queries of the form 2 containing the required answer for the corresponding query just after the query. 7 3 0 3 5 1 0 6 3 <-- this is the first output 1 3 4 2 <-- this is output
SAMPLE INPUT 7 3 0 3 5 1 0 6 1 3 4
SAMPLE OUTPUT 3 2
Assistant
class SegmentTree: def __init__(self, size): self.n = size self.tree = [0] * (4 * self.n) self.lazy = [False] * (4 * self.n) def push(self, node, l, r): if self.lazy[node]: mid = (l + r) // 2 left = 2 * node + 1 right_node = 2 * node + 2 # Flip left child self.tree[left] = (mid - l + 1) - self.tree[left] self.lazy[left] = not self.lazy[left] # Flip right child self.tree[right_node] = (r - mid) - self.tree[right_node] self.lazy[right_node] = not self.lazy[right_node] # Clear the lazy flag for current node self.lazy[node] = False def update_range(self, a, b, node=0, l=0, r=None): if r is None: r = self.n - 1 if a > r or b < l: return if a <= l and r <= b: # Apply flip to current node self.tree[node] = (r - l + 1) - self.tree[node] self.lazy[node] = not self.lazy[node] return self.push(node, l, r) mid = (l + r) // 2 self.update_range(a, b, 2*node+1, l, mid) self.update_range(a, b, 2*node+2, mid+1, r) self.tree[node] = self.tree[2*node+1] + self.tree[2*node+2] def query_range(self, a, b, node=0, l=0, r=None): if r is None: r = self.n - 1 if a > r or b < l: return 0 if a <= l and r <= b: return self.tree[node] self.push(node, l, r) mid = (l + r) // 2 return self.query_range(a, b, 2*node+1, l, mid) + self.query_range(a, b, 2*node+2, mid+1, r) n = int(input()) q = int(input()) st = SegmentTree(n) for _ in range(q): op = int(input()) a = int(input()) b = int(input()) if op == 0: st.update_range(a, b) else: print(st.query_range(a, b))
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.