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