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