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, data_length): self.n = data_length self.size = 1 while self.size < self.n: self.size <<= 1 self.tree = [0] * (2 * self.size) self.lazy = [0] * (2 * self.size) def _apply(self, node, l, r): self.tree[node] = (r - l + 1) - self.tree[node] if node < self.size: self.lazy[node] ^= 1 def _push(self, node, l, r): if self.lazy[node]: mid = (l + r) // 2 left = 2 * node self._apply(left, l, mid) right_child = 2 * node + 1 self._apply(right_child, mid + 1, r) self.lazy[node] = 0 def flip_range(self, a, b): def _flip(l, r, node, node_l, node_r): if r < node_l or l > node_r: return if l <= node_l and node_r <= r: self._apply(node, node_l, node_r) return self._push(node, node_l, node_r) mid = (node_l + node_r) // 2 _flip(l, r, 2 * node, node_l, mid) _flip(l, r, 2 * node + 1, mid + 1, node_r) self.tree[node] = self.tree[2 * node] + self.tree[2 * node + 1] _flip(a, b, 1, 0, self.size - 1) def query_range(self, a, b): res = 0 def _query(l, r, node, node_l, node_r): nonlocal res if r < node_l or l > node_r: return if l <= node_l and node_r <= r: res += self.tree[node] return self._push(node, node_l, node_r) mid = (node_l + node_r) // 2 _query(l, r, 2 * node, node_l, mid) _query(l, r, 2 * node + 1, mid + 1, node_r) _query(a, b, 1, 0, self.size - 1) return res 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.flip_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.