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.flip = False def push_down(self): if self.flip and self.l != self.r: if not self.left or not self.right: mid = (self.l + self.r) // 2 self.left = SegmentTreeNode(self.l, mid) self.right = SegmentTreeNode(mid + 1, self.r) self.left.flip = not self.left.flip self.left.count = (self.left.r - self.left.l + 1) - self.left.count self.right.flip = not self.right.flip self.right.count = (self.right.r - self.right.l + 1) - self.right.count self.flip = False def flip(l, r, node): if node.r < l or node.l > r: return if l <= node.l and node.r <= r: node.count = (node.r - node.l + 1) - node.count node.flip = not node.flip return if not node.left or not node.right: mid = (node.l + node.r) // 2 node.left = SegmentTreeNode(node.l, mid) node.right = SegmentTreeNode(mid + 1, node.r) node.push_down() flip(l, r, node.left) flip(l, r, node.right) node.count = node.left.count + node.right.count def query(l, r, node): if node.r < l or node.l > r: return 0 if l <= node.l and node.r <= r: return node.count if not node.left or not node.right: mid = (node.l + node.r) // 2 node.left = SegmentTreeNode(node.l, mid) node.right = SegmentTreeNode(mid + 1, node.r) node.push_down() return query(l, r, node.left) + query(l, r, node.right) import sys data = list(map(int, sys.stdin.read().split())) idx = 0 n = data[idx] idx += 1 q = data[idx] idx += 1 root = SegmentTreeNode(0, n - 1) for _ in range(q): cmd = data[idx] a = data[idx + 1] b = data[idx + 2] idx += 3 if cmd == 0: flip(a, b, root) else: res = query(a, b, root) 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.