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 build(start, end): node = SegmentTreeNode(start, end) if start == end: return node mid = (start + end) // 2 node.left = build(start, mid) node.right = build(mid+1, end) return node def update_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 node.left or node.right: node.flip = not node.flip return propagate(node) update_range(node.left, l, r) update_range(node.right, l, r) node.sum = node.left.sum + node.right.sum def propagate(node): if node.flip and node.left: left = node.left left.sum = (left.end - left.start + 1) - left.sum left.flip = not left.flip right = node.right right.sum = (right.end - right.start + 1) - right.sum right.flip = not right.flip node.flip = False 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 propagate(node) return query_range(node.left, l, r) + query_range(node.right, l, r) def main(): input = sys.stdin.read().split() ptr = 0 n = int(input[ptr]) ptr += 1 q = int(input[ptr]) ptr += 1 root = build(0, n-1) for _ in range(q): cmd = int(input[ptr]) ptr += 1 a = int(input[ptr]) ptr += 1 b = int(input[ptr]) ptr += 1 if cmd == 0: update_range(root, a, b) else: print(query_range(root, a, b)) 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.