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.size_tree = 1 while self.size_tree < self.n: self.size_tree <<= 1 self.tree = [0] * (2 * self.size_tree) self.lazy = [False] * (2 * self.size_tree) def push(self, node, l, r): if self.lazy[node]: self.tree[node] = (r - l) - self.tree[node] if (r - l) > 1: self.lazy[2*node+1] ^= True self.lazy[2*node+2] ^= True self.lazy[node] = False def update_range(self, a, b, node=0, l=0, r=None): if r is None: r = self.size_tree a = max(a, 0) b = min(b, self.n) if a >= b: return self.push(node, l, r) if a >= r or b <= l: return if a <= l and r <= b: self.lazy[node] ^= True self.push(node, l, r) return mid = (l + r) // 2 self.update_range(a, b, 2*node+1, l, mid) self.update_range(a, b, 2*node+2, mid, 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.size_tree a = max(a, 0) b = min(b, self.n) if a >= b: return 0 self.push(node, l, r) if a >= r or b <= l: return 0 if a <= l and r <= b: return self.tree[node] mid = (l + r) // 2 left = self.query_range(a, b, 2*node+1, l, mid) right = self.query_range(a, b, 2*node+2, mid, r) return left + right n = int(input()) q = int(input()) st = SegmentTree(n) for _ in range(q): cmd = int(input()) a = int(input()) b = int(input()) if cmd == 0: st.update_range(a, b + 1) else: res = st.query_range(a, b + 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.