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): self.n = len(data) self.size = 1 while self.size < self.n: self.size <<= 1 self.tree = [0] * (2 * self.size) self.lazy = [False] * (2 * self.size) for i in range(self.n): self.tree[self.size + i] = data[i] for i in range(self.size - 1, 0, -1): self.tree[i] = self.tree[2*i] + self.tree[2*i+1] def _push(self, node, l, r): if self.lazy[node]: mid = (l + r) // 2 left = 2 * node right_node = 2 * node + 1 self.tree[left] = (mid - l + 1) - self.tree[left] self.lazy[left] = not self.lazy[left] self.tree[right_node] = (r - mid) - self.tree[right_node] self.lazy[right_node] = not self.lazy[right_node] self.lazy[node] = False def update_range(self, a, b): def _update(node, node_l, node_r): if node_r < a or node_l > b: return if a <= node_l and node_r <= b: self.tree[node] = (node_r - node_l + 1) - self.tree[node] self.lazy[node] = not self.lazy[node] else: self._push(node, node_l, node_r) mid = (node_l + node_r) // 2 _update(2*node, node_l, mid) _update(2*node+1, mid+1, node_r) self.tree[node] = self.tree[2*node] + self.tree[2*node+1] _update(1, 0, self.size - 1) def query_range(self, a, b): res = 0 def _query(node, node_l, node_r): nonlocal res if node_r < a or node_l > b: return if a <= node_l and node_r <= b: res += self.tree[node] else: self._push(node, node_l, node_r) mid = (node_l + node_r) // 2 _query(2*node, node_l, mid) _query(2*node+1, mid+1, node_r) _query(1, 0, self.size - 1) return res def main(): import sys input = sys.stdin.read().split() ptr = 0 n = int(input[ptr]) ptr +=1 q = int(input[ptr]) ptr +=1 data = [0]*n st = SegmentTree(data) for _ in range(q): cmd = input[ptr] ptr +=1 a = int(input[ptr]) ptr +=1 b = int(input[ptr]) ptr +=1 if cmd == '0': st.update_range(a, b) else: print(st.query_range(a, b)) if __name__ == "__main__": main()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.