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 SegmentTree: def __init__(self, size): self.n = size self.size = 1 while self.size < self.n: self.size <<= 1 self.sum = [0] * (2 * self.size) self.lazy = [0] * (2 * self.size) def push(self, node, l, r): if self.lazy[node] != 0: mid = (l + r) // 2 left_node = 2 * node right_node = 2 * node + 1 # Apply toggle to left child self.sum[left_node] = (mid - l + 1) - self.sum[left_node] self.lazy[left_node] ^= 1 # Apply toggle to right child self.sum[right_node] = (r - mid) - self.sum[right_node] self.lazy[right_node] ^= 1 # Clear the lazy flag for the current node self.lazy[node] = 0 def update_range(self, a, b, node=1, l=0, r=None): if r is None: r = self.size - 1 if a > r or b < l: return if a <= l and r <= b: # Toggle the current node's sum and mark lazy self.sum[node] = (r - l + 1) - self.sum[node] self.lazy[node] ^= 1 return self.push(node, l, r) mid = (l + r) // 2 self.update_range(a, b, 2*node, l, mid) self.update_range(a, b, 2*node+1, mid+1, r) self.sum[node] = self.sum[2*node] + self.sum[2*node+1] def query_range(self, a, b, node=1, l=0, r=None): if r is None: r = self.size - 1 if a > r or b < l: return 0 if a <= l and r <= b: return self.sum[node] self.push(node, l, r) mid = (l + r) // 2 return self.query_range(a, b, 2*node, l, mid) + self.query_range(a, b, 2*node+1, mid+1, r) # Read input n = int(sys.stdin.readline()) q = int(sys.stdin.readline()) st = SegmentTree(n) for _ in range(q): cmd = sys.stdin.readline().strip() a = int(sys.stdin.readline().strip()) b = int(sys.stdin.readline().strip()) if cmd == '0': st.update_range(a, b) else: print(st.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.