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.lazy = False def push(self): if self.lazy: if self.l != self.r: mid = (self.l + self.r) // 2 if not self.left: self.left = SegmentTreeNode(self.l, mid) if not self.right: self.right = SegmentTreeNode(mid + 1, self.r) self.left.sum = (mid - self.l + 1) - self.left.sum self.left.lazy = not self.left.lazy self.right.sum = (self.r - mid) - self.right.sum self.right.lazy = not self.right.lazy self.lazy = False def update(self, a, b): if a > self.r or b < self.l: return if a <= self.l and self.r <= b: self.sum = (self.r - self.l + 1) - self.sum self.lazy = not self.lazy return self.push() mid = (self.l + self.r) // 2 if not self.left: self.left = SegmentTreeNode(self.l, mid) if not self.right: self.right = SegmentTreeNode(mid + 1, self.r) self.left.update(a, b) self.right.update(a, b) self.sum = self.left.sum + self.right.sum def query(self, a, b): if a > self.r or b < self.l: return 0 if a <= self.l and self.r <= b: return self.sum self.push() res = 0 if self.left: res += self.left.query(a, b) if self.right: res += self.right.query(a, b) return res n = int(input()) q = int(input()) root = SegmentTreeNode(0, n - 1) for _ in range(q): op = int(input()) a = int(input()) b = int(input()) if op == 0: root.update(a, b) else: print(root.query(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.