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.data = data self.sum_tree = [0] * (4 * self.n) self.lazy = [0] * (4 * self.n) self.build(0, self.n - 1, 1) def build(self, l, r, node): if l == r: self.sum_tree[node] = self.data[l] return mid = (l + r) // 2 self.build(l, mid, 2 * node) self.build(mid + 1, r, 2 * node + 1) self.sum_tree[node] = self.sum_tree[2 * node] + self.sum_tree[2 * node + 1] def push(self, node, l, r): if self.lazy[node] != 0: mid = (l + r) // 2 left_node = 2 * node right_node = 2 * node + 1 self.sum_tree[left_node] = (mid - l + 1) - self.sum_tree[left_node] self.lazy[left_node] ^= self.lazy[node] self.sum_tree[right_node] = (r - mid) - self.sum_tree[right_node] self.lazy[right_node] ^= self.lazy[node] self.lazy[node] = 0 def update_range(self, a, b, l, r, node): if a > r or b < l: return if a <= l and r <= b: self.sum_tree[node] = (r - l + 1) - self.sum_tree[node] self.lazy[node] ^= 1 return self.push(node, l, r) mid = (l + r) // 2 self.update_range(a, b, l, mid, 2 * node) self.update_range(a, b, mid + 1, r, 2 * node + 1) self.sum_tree[node] = self.sum_tree[2 * node] + self.sum_tree[2 * node + 1] def query_range(self, a, b, l, r, node): if a > r or b < l: return 0 if a <= l and r <= b: return self.sum_tree[node] self.push(node, l, r) mid = (l + r) // 2 left_sum = self.query_range(a, b, l, mid, 2 * node) right_sum = self.query_range(a, b, mid + 1, r, 2 * node + 1) return left_sum + right_sum n = int(input()) q = int(input()) data = [0] * n st = SegmentTree(data) for _ in range(q): parts = [] while len(parts) < 3: parts += input().split() cmd = int(parts[0]) a = int(parts[1]) b = int(parts[2]) a_clamped = max(0, a) b_clamped = min(b, n-1) if a_clamped > b_clamped: if cmd == 1: print(0) continue if cmd == 0: st.update_range(a_clamped, b_clamped, 0, n-1, 1) else: res = st.query_range(a_clamped, b_clamped, 0, n-1, 1) print(res)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.