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
import sys class SegmentTreeNode: def __init__(self, start, end): self.start = start self.end = end self.left = None self.right = None self.sum = 0 self.flip = False def is_leaf(self): return self.start == self.end def build(start, end): node = SegmentTreeNode(start, end) if start == end: node.sum = 0 else: mid = (start + end) // 2 node.left = build(start, mid) node.right = build(mid + 1, end) node.sum = node.left.sum + node.right.sum return node def flip_range(node, l, r): if node.end < l or node.start > r: return if l <= node.start and node.end <= r: node.sum = (node.end - node.start + 1) - node.sum if not node.is_leaf(): node.flip = not node.flip return if node.flip: node.left.sum = (node.left.end - node.left.start + 1) - node.left.sum node.left.flip = not node.left.flip node.right.sum = (node.right.end - node.right.start + 1) - node.right.sum node.right.flip = not node.right.flip node.flip = False flip_range(node.left, l, r) flip_range(node.right, l, r) node.sum = node.left.sum + node.right.sum def query_range(node, l, r): if node.end < l or node.start > r: return 0 if l <= node.start and node.end <= r: return node.sum if node.flip: node.left.sum = (node.left.end - node.left.start + 1) - node.left.sum node.left.flip = not node.left.flip node.right.sum = (node.right.end - node.right.start + 1) - node.right.sum node.right.flip = not node.right.flip node.flip = False return query_range(node.left, l, r) + query_range(node.right, l, r) def main(): data = list(map(int, sys.stdin.read().split())) ptr = 0 N = data[ptr] ptr += 1 Q = data[ptr] ptr += 1 root = build(0, N - 1) for _ in range(Q): cmd = data[ptr] ptr += 1 A = data[ptr] ptr += 1 B = data[ptr] ptr += 1 if cmd == 0: flip_range(root, A, B) else: res = query_range(root, A, B) print(res) 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.