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 SegmentTreeNode: def __init__(self, l, r): self.l = l self.r = r self.left = None self.right = None self.count = 0 self.lazy = 0 class SegmentTree: def __init__(self, n): self.root = self.build(0, n-1) def build(self, l, r): node = SegmentTreeNode(l, r) if l == r: return node mid = (l + r) // 2 node.left = self.build(l, mid) node.right = self.build(mid+1, r) return node def push(self, node): if node.lazy and node.left: left = node.left left.count = (left.r - left.l + 1) - left.count left.lazy ^= 1 right = node.right right.count = (right.r - right.l + 1) - right.count right.lazy ^= 1 node.lazy = 0 def update_range(self, a, b, node): if node.r < a or node.l > b: return if a <= node.l and node.r <= b: node.count = (node.r - node.l + 1) - node.count node.lazy ^= 1 return self.push(node) self.update_range(a, b, node.left) self.update_range(a, b, node.right) node.count = node.left.count + node.right.count def query_range(self, a, b, node): if node.r < a or node.l > b: return 0 if a <= node.l and node.r <= b: return node.count self.push(node) return self.query_range(a, b, node.left) + self.query_range(a, b, node.right) n = int(input()) q = int(input()) st = SegmentTree(n) for _ in range(q): cmd = input().strip() while cmd == '': cmd = input().strip() if cmd == '0': A = int(input()) B = int(input()) st.update_range(A, B, st.root) elif cmd == '1': A = int(input()) B = int(input()) print(st.query_range(A, B, st.root))
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.