message
stringlengths
2
48.6k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
318
108k
cluster
float64
8
8
__index_level_0__
int64
636
217k
Provide tags and a correct Python 3 solution for this coding contest problem. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too.
instruction
0
56,563
8
113,126
Tags: data structures, implementation Correct Solution: ``` import sys int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] class BitSum: def __init__(self, n): self.n = n+1 self.table = [0]*self.n def add(self, i, x): i += 1 while i < self.n: self.table[i] += x i += i & -i def sum(self, i): i += 1 res = 0 while i > 0: res += self.table[i] i -= i & -i return res def pos(self, x): idx = 0 for lv in range((self.n-1).bit_length()-1, -1, -1): mid = idx+(1 << lv) if mid >= self.n: continue if self.table[mid] < x: x -= self.table[mid] idx += 1 << lv return idx # θ¦η΄ γ‚’ε…ˆθͺ­γΏγ™γ‚‹δ»£γ‚γ‚Šγ«γ€[0,10**6]でγͺγγ¨γ‚‚δ½Ώγˆγ‚‹ class Cset: def __init__(self, aa): aa = set(aa) self.dec = tuple(sorted(aa)) self.enc = {a: i for i, a in enumerate(self.dec)} self.mx = len(self.dec) self.size = 0 self.bit = BitSum(self.mx+1) self.nums = [False]*(self.mx+1) def __repr__(self): return " ".join(str(self[i]) for i in range(self.size)) def insert(self, a): if a not in self.enc: return False a = self.enc[a] if a < 0 or a > self.mx or self.nums[a]: return False self.size += 1 self.bit.add(a, 1) self.nums[a] = True return True def remove(self, value): if value not in self.enc: return False value = self.enc[value] if value < 0 or value > self.mx or not self.nums[value]: return False self.size -= 1 self.bit.add(value, -1) self.nums[value] = False return True def erase(self, index): i = index if i >= self.size or i < -self.size: return False if i < 0: i = self.size+i+1 else: i += 1 a = self.bit.pos(i) self.size -= 1 self.bit.add(a, -1) self.nums[a] = False return True def __getitem__(self, i): if i >= self.size or i < -self.size: return -1 if i < 0: i = self.size+i+1 else: i += 1 return self.dec[self.bit.pos(i)] def __contains__(self, item): return self.nums[self.enc[item]] def __len__(self): return self.size def bisect_left(self, a): if a not in self.enc: return -1 a = self.enc[a] if a < 0 or a > self.mx: return -1 if a == 0: return 0 return self.bit.sum(a-1) def bisect_right(self, a): if a not in self.enc: return -1 a = self.enc[a] if a < 0 or a > self.mx: return -1 return self.bit.sum(a) class RemovableHeap: def __init__(self): self.hp = [] self.rem = [] self.s = {} self.size = 0 def __len__(self): return self.size def __getitem__(self, i): if i: return None self.__trim() return self.hp[0] def push(self, val): heappush(self.hp, val) if val in self.s: self.s[val] += 1 else: self.s[val] = 1 self.size += 1 return True def pop(self): self.__trim() if not self.hp: return None self.size -= 1 val = heappop(self.hp) if self.s[val] == 1: del self.s[val] else: self.s[val] -= 1 return val def remove(self, val): if val not in self.s: return False self.size -= 1 if self.s[val] == 1: del self.s[val] else: self.s[val] -= 1 heappush(self.rem, val) return True def __trim(self): while self.rem and self.rem[0] == self.hp[0]: heappop(self.hp) heappop(self.rem) from heapq import * mx = 200005 n, q = MI() pp = LI() tx = LLI(q) st = Cset(pp+[x for t, x in tx]) for p in pp: st.insert(p) pp.sort() hp = RemovableHeap() for i in range(n-1): hp.push(-pp[i+1]+pp[i]) w = pp[-1]-pp[0] if len(hp): print(w+hp[0]) else: print(0) for t, x in tx: i = st.bisect_left(x) if t: if i == 0: if len(st) > 0: p = st[0] hp.push(x-p) w += p-x elif i == len(st): p = st[-1] hp.push(p-x) w += x-p else: pl = st[i-1] pr = st[i] hp.push(pl-x) hp.push(x-pr) hp.remove(pl-pr) st.insert(x) else: if i == 0: if len(st) > 1: pl = st[0] pr = st[1] hp.remove(pl-pr) w -= pr-pl elif i == len(st)-1: pl = st[-2] pr = st[-1] hp.remove(pl-pr) w -= pr-pl else: pl = st[i-1] pr = st[i+1] hp.push(pl-pr) hp.remove(pl-x) hp.remove(x-pr) st.remove(x) # print(st) # print(hp.hp) # print(hp.rem) # print("w=", w) if len(hp): print(w+hp[0]) else: print(0) ```
output
1
56,563
8
113,127
Provide tags and a correct Python 3 solution for this coding contest problem. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too.
instruction
0
56,564
8
113,128
Tags: data structures, implementation Correct Solution: ``` #import bisect import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline class Sortedlist: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list. if value > bigger element, it returns len """ pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) n,q = map(int,input().split()) arr = list(map(int,input().split())) arr = sorted(arr) d = [0] for i in range(n-1): d.append(arr[i+1]-arr[i]) sorted_arr = Sortedlist(arr) sorted_d = Sortedlist(d) #print(sorted_arr) #print(sorted_arr[-1]-sorted_arr[0]) print(sorted_arr[-1]-sorted_arr[0]-sorted_d[-1]) #print("---",arr,d) for j in range(q): op, x = map(int,input().split()) if op==0: loc = sorted_arr.bisect_left(x) frontd,reard = 0,0 if 0<loc<len(sorted_arr): frontd = sorted_arr[loc] - sorted_arr[loc-1] if loc<len(sorted_arr)-1: reard = sorted_arr[loc+1] - sorted_arr[loc] sorted_arr.pop(loc) if frontd>0: loc1 = sorted_d.bisect_left(frontd) sorted_d.pop(loc1) if reard>0: loc2 = sorted_d.bisect_left(reard) sorted_d.pop(loc2) if frontd>0 and reard>0: sorted_d.add(frontd+reard) else: loc = sorted_arr.bisect_left(x) frontd,reard = 0,0 if loc>0: frontd = x - sorted_arr[loc-1] if loc<len(sorted_arr): reard = sorted_arr[loc] - x sorted_arr.add(x) if frontd>0: sorted_d.add(frontd) if reard>0: sorted_d.add(reard) if frontd>0 and reard>0: loct = sorted_d.bisect_left(frontd+reard) sorted_d.pop(loct) if len(sorted_arr)>0 and len(sorted_d)>0: print(sorted_arr[-1]-sorted_arr[0]-sorted_d[-1]) else: print(0) # print(sorted_arr) # print(sorted_d) ```
output
1
56,564
8
113,129
Provide tags and a correct Python 3 solution for this coding contest problem. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too.
instruction
0
56,565
8
113,130
Tags: data structures, implementation Correct Solution: ``` # -*- coding: utf-8 -*- import sys # sys.setrecursionlimit(10**6) # readline = sys.stdin.buffer.readline readline = sys.stdin.readline INF = 1 << 60 def read_int(): return int(readline()) def read_int_n(): return list(map(int, readline().split())) def read_float(): return float(readline()) def read_float_n(): return list(map(float, readline().split())) def read_str(): return readline().strip() def read_str_n(): return readline().strip().split() def ep(*args): print(*args, file=sys.stderr) def mt(f): import time def wrap(*args, **kwargs): s = time.perf_counter() ret = f(*args, **kwargs) e = time.perf_counter() ep(e - s, 'sec') return ret return wrap class SegmentTree: def __init__(self, array, operator, identity_element): _len = len(array) self.__len = _len self.__op = operator self.__size = 1 << (_len - 1).bit_length() self.__tree = [identity_element] * self.__size + \ array + [identity_element] * (self.__size - _len) self.__ie = identity_element for i in range(self.__size - 1, 0, -1): self.__tree[i] = operator( self.__tree[i * 2], self.__tree[i * 2 + 1]) def update(self, i, v): i += self.__size self.__tree[i] = v while i: i //= 2 self.__tree[i] = self.__op(self.__tree[i * 2], self.__tree[i * 2 + 1]) def query(self, l, r): """[l, r) """ l += self.__size r += self.__size ret = self.__ie while l < r: if l & 1: ret = self.__op(ret, self.__tree[l]) l += 1 if r & 1: r -= 1 ret = self.__op(ret, self.__tree[r]) l //= 2 r //= 2 return ret def max_right(self, l, f): # https://atcoder.jp/contests/practice2/submissions/16636885 assert 0 <= l <= self.__len if l == self.__len: return self.__len l += self.__size sm = self.__ie while True: while l % 2 == 0: l >>= 1 if not f(self.__op(sm, self.__tree[l])): while l < self.__size: l = 2*l if f(self.__op(sm, self.__tree[l])): sm = self.__op(sm, self.__tree[l]) l += 1 return l - self.__size sm = self.__op(sm, self.__tree[l]) l += 1 if (l & -l) == l: break return self.__len def min_left(self, r, f): assert 0 <= r <= self.__len if r == 0: return 0 r += self.__size sm = self.__ie while True: r -= 1 while r > 1 and (r % 2): r >>= 1 if not f(self.__op(sm, self.__tree[r])): while r < self.__size: r = 2*r + 1 if f(self.__op(sm, self.__tree[r])): sm = self.__op(sm, self.__tree[r]) r -= 1 return r + 1 - self.__size sm = self.__op(sm, self.__tree[r]) if (r & -r) == r: break return 0 def __getitem__(self, key): return self.__tree[key + self.__size] from heapq import heappop, heappush from collections import Counter class UpdatableHeapQueue: def __init__(self): self.__q = [] self.__cc = Counter() def add(self, v, k): heappush(self.__q, (v, k)) self.__cc[k] += 1 def remove(self, k): self.__cc[k] -= 1 def refrash(self): while self.__q: if self.__cc[self.__q[0][1]] == 0: heappop(self.__q) else: break def pop(self): self.refrash() return heappop(self.__q) def peek(self): self.refrash() return self.__q[0] def empty(self): self.refrash() return len(self.__q) == 0 # @mt def slv(N, P, Q): p = P[:] + [x for _, x in Q] p.sort() p2i = {p: i for i, p in enumerate(p)} i2p = p M = len(i2p) lst = SegmentTree([-INF]*M, max, -INF) rst = SegmentTree([INF]*M, min, INF) for x in P: i = p2i[x] lst.update(i, i) rst.update(i, i) q = UpdatableHeapQueue() P.sort() for i in range(len(P)-1): d = P[i+1] - P[i] ai, bi = p2i[P[i]], p2i[P[i+1]] q.add(-d, (ai, bi)) def add(x): ci = p2i[x] ai = lst.query(0, ci) bi = rst.query(ci+1, M) lst.update(ci, ci) rst.update(ci, ci) if ai != -INF: q.add(-(i2p[ci]-i2p[ai]), (ai, ci)) if bi != INF: q.add(-(i2p[bi]-i2p[ci]), (ci, bi)) if ai != -INF and bi != INF: q.remove((ai, bi)) return q.peek() if not q.empty() else (0, (None, None)) def remove(x): ci = p2i[x] lst.update(ci, -INF) rst.update(ci, INF) ai = lst.query(0, ci) bi = rst.query(ci+1, M) if ai != -INF: q.remove((ai, ci)) if bi != INF: q.remove((ci, bi)) if ai != -INF and bi != INF: q.add(-(i2p[bi]-i2p[ai]), (ai, bi)) return q.peek() if not q.empty() else (0, (None, None)) if not q.empty(): ans = [max(P) - min(P) + q.peek()[0]] else: ans = [0] for t, x in Q: if t == 0: a = remove(x) else: a = add(x) li = lst.query(0, M) ri = rst.query(0, M) if li != -INF: l = i2p[li] r = i2p[ri] if l == r: ans.append(0) else: ans.append(l-r+a[0]) else: ans.append(0) return ans def main(): N, Q = read_int_n() P = read_int_n() Q = [read_int_n() for _ in range(Q)] print(*slv(N, P, Q), sep='\n') if __name__ == '__main__': main() ```
output
1
56,565
8
113,131
Provide tags and a correct Python 3 solution for this coding contest problem. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too.
instruction
0
56,566
8
113,132
Tags: data structures, implementation Correct Solution: ``` class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if not True else 1): n, q = map(int, input().split()) a = sorted(list(map(int, input().split()))) sl = SortedList(a) sl2 = SortedList([a[i] - a[i-1] for i in range(1, n)]) count = n for __ in range(q+1): high, low = sl.__getitem__(count - 1) if count else 0, sl.__getitem__(0) if count else 0 if __: t, x = map(int, input().split()) if t == 1: if count == 0: pass elif x < low: sl2.add(low - x) low = x elif x > high: sl2.add(x - high) high = x else: p = sl.__getitem__(sl.bisect_left(x) - 1) q = sl.__getitem__(sl.bisect_right(x)) sl2.add(x-p) sl2.add(q-x) sl2.remove(q-p) count += 1 sl.add(x) else: if x == low: if count > 1: low = sl.__getitem__(1) sl2.remove(low - x) elif x == high: if count > 1: high = sl.__getitem__(count-2) sl2.remove(x - high) else: p = sl.__getitem__(sl.bisect_left(x) - 1) q = sl.__getitem__(sl.bisect_right(x)) sl2.remove(x - p) sl2.remove(q - x) sl2.add(q - p) sl.remove(x) count -= 1 if count <= 2: print(0) continue maxdiff = sl2.__getitem__(count-2) print(high - low - maxdiff) ```
output
1
56,566
8
113,133
Provide tags and a correct Python 3 solution for this coding contest problem. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too.
instruction
0
56,567
8
113,134
Tags: data structures, implementation Correct Solution: ``` # -*- coding: utf-8 -*- from heapq import heappop, heappush from collections import Counter import sys # sys.setrecursionlimit(10**6) # readline = sys.stdin.buffer.readline readline = sys.stdin.readline INF = 1 << 60 def read_int(): return int(readline()) def read_int_n(): return list(map(int, readline().split())) def read_float(): return float(readline()) def read_float_n(): return list(map(float, readline().split())) def read_str(): return readline().strip() def read_str_n(): return readline().strip().split() def ep(*args): print(*args, file=sys.stderr) def mt(f): import time def wrap(*args, **kwargs): s = time.perf_counter() ret = f(*args, **kwargs) e = time.perf_counter() ep(e - s, 'sec') return ret return wrap class SegmentTree: def __init__(self, array, operator, identity_element): _len = len(array) self.__len = _len self.__op = operator self.__size = 1 << (_len - 1).bit_length() self.__tree = [identity_element] * self.__size + \ array + [identity_element] * (self.__size - _len) self.__ie = identity_element for i in range(self.__size - 1, 0, -1): self.__tree[i] = operator( self.__tree[i * 2], self.__tree[i * 2 + 1]) def update(self, i, v): i += self.__size self.__tree[i] = v while i: i //= 2 self.__tree[i] = self.__op( self.__tree[i * 2], self.__tree[i * 2 + 1]) def query(self, l, r): """[l, r) """ l += self.__size r += self.__size ret = self.__ie while l < r: if l & 1: ret = self.__op(ret, self.__tree[l]) l += 1 if r & 1: r -= 1 ret = self.__op(ret, self.__tree[r]) l //= 2 r //= 2 return ret def max_right(self, l, f): # https://atcoder.jp/contests/practice2/submissions/16636885 assert 0 <= l <= self.__len if l == self.__len: return self.__len l += self.__size sm = self.__ie while True: while l % 2 == 0: l >>= 1 if not f(self.__op(sm, self.__tree[l])): while l < self.__size: l = 2*l if f(self.__op(sm, self.__tree[l])): sm = self.__op(sm, self.__tree[l]) l += 1 return l - self.__size sm = self.__op(sm, self.__tree[l]) l += 1 if (l & -l) == l: break return self.__len def min_left(self, r, f): assert 0 <= r <= self.__len if r == 0: return 0 r += self.__size sm = self.__ie while True: r -= 1 while r > 1 and (r % 2): r >>= 1 if not f(self.__op(sm, self.__tree[r])): while r < self.__size: r = 2*r + 1 if f(self.__op(sm, self.__tree[r])): sm = self.__op(sm, self.__tree[r]) r -= 1 return r + 1 - self.__size sm = self.__op(sm, self.__tree[r]) if (r & -r) == r: break return 0 def __getitem__(self, key): return self.__tree[key + self.__size] class RemovableHeapQueue: def __init__(self): self.__q = [] self.__cc = Counter() def add(self, v, k): heappush(self.__q, (v, k)) self.__cc[k] += 1 def remove(self, k): self.__cc[k] -= 1 assert self.__cc[k] >= 0 def refrash(self): while self.__q: if self.__cc[self.__q[0][1]] == 0: heappop(self.__q) else: break def pop(self): self.refrash() return heappop(self.__q) def top(self): self.refrash() return self.__q[0] def empty(self): self.refrash() return len(self.__q) == 0 # @mt def slv(N, P, Q): p = P[:] + [x for _, x in Q] p.sort() p2i = {p: i for i, p in enumerate(p)} i2p = p M = len(i2p) lst = SegmentTree([-INF]*M, max, -INF) rst = SegmentTree([INF]*M, min, INF) for x in P: i = p2i[x] lst.update(i, i) rst.update(i, i) q = RemovableHeapQueue() P.sort() for i in range(len(P)-1): d = P[i+1] - P[i] ai, bi = p2i[P[i]], p2i[P[i+1]] q.add(-d, (ai, bi)) def add(x): ci = p2i[x] ai = lst.query(0, ci) bi = rst.query(ci+1, M) lst.update(ci, ci) rst.update(ci, ci) if ai != -INF: q.add(-(i2p[ci]-i2p[ai]), (ai, ci)) if bi != INF: q.add(-(i2p[bi]-i2p[ci]), (ci, bi)) if ai != -INF and bi != INF: q.remove((ai, bi)) return q.top() if not q.empty() else (0, (None, None)) def remove(x): ci = p2i[x] lst.update(ci, -INF) rst.update(ci, INF) ai = lst.query(0, ci) bi = rst.query(ci+1, M) if ai != -INF: q.remove((ai, ci)) if bi != INF: q.remove((ci, bi)) if ai != -INF and bi != INF: q.add(-(i2p[bi]-i2p[ai]), (ai, bi)) return q.top() if not q.empty() else (0, (None, None)) if not q.empty(): ans = [max(P) - min(P) + q.top()[0]] else: ans = [0] for t, x in Q: if t == 0: a = remove(x) else: a = add(x) li = lst.query(0, M) ri = rst.query(0, M) if li != -INF: l = i2p[li] r = i2p[ri] if l == r: ans.append(0) else: ans.append(l-r+a[0]) else: ans.append(0) return ans def main(): # 2 N, Q = read_int_n() P = read_int_n() Q = [read_int_n() for _ in range(Q)] print(*slv(N, P, Q), sep='\n') if __name__ == '__main__': main() ```
output
1
56,567
8
113,135
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. Submitted Solution: ``` import io import os from collections import Counter, defaultdict, deque # https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size : _size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) class Node: def __init__(self, count, mn, mx, maxGap): self.count = count self.mn = mn self.mx = mx self.maxGap = maxGap neutral = Node(0, 0, 0, 0) def combine(x, y): if x.count == 0: return y if y.count == 0: return x return Node( x.count + y.count, min(x.mn, y.mn), max(y.mx, y.mx), max(y.mn - x.mx, x.maxGap, y.maxGap), ) def solve(N, Q, P, TX): allPoints = sorted(set(P + [x for t, x in TX])) compress = {} for i, x in enumerate(allPoints): compress[x] = i counts = [0] * len(allPoints) segTree = SegmentTree([neutral] * len(allPoints), neutral, combine) for x in P: index = compress[x] counts[index] += 1 segTree[index] = Node(counts[index], x, x, 0) def query(): node = segTree.query(0, len(allPoints)) if node.count == 1: return 0 return node.mx - node.mn - node.maxGap ans = [query()] for t, x in TX: index = compress[x] if t == 0: counts[index] -= 1 else: counts[index] += 1 assert t == 1 segTree[index] = Node(counts[index], x, x, 0) ans.append(query()) return "\n".join(map(str, ans)) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, Q = [int(x) for x in input().split()] P = [int(x) for x in input().split()] TX = [[int(x) for x in input().split()] for i in range(Q)] ans = solve(N, Q, P, TX) print(ans) ```
instruction
0
56,568
8
113,136
Yes
output
1
56,568
8
113,137
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase _str = str BUFSIZE = 8192 def str(x=b''): return x if type(x) is bytes else _str(x).encode() class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def inp(): return sys.stdin.readline() def mpint(): return map(int, sys.stdin.readline().split(' ')) def itg(): return int(sys.stdin.readline()) # ############################## import from heapq import * class Fenwick: """ Simpler FenwickTree """ def __init__(self, x): self.bit = [0] * x def update(self, idx, x): """updates bit[idx] += x""" while idx < len(self.bit): self.bit[idx] += x idx |= idx + 1 def query(self, end): """calc sum(bit[:end])""" x = 0 while end: x += self.bit[end - 1] end &= end - 1 return x def findkth(self, k): """ Find largest idx such that sum(bit[:idx]) < k (!) different from pyrival (just removed the '=') """ idx = -1 for d in reversed(range(len(self.bit).bit_length())): right_idx = idx + (1 << d) if right_idx < len(self.bit) and k > self.bit[right_idx]: idx = right_idx k -= self.bit[idx] return idx + 1 class Cset: def __init__(self, discrete_data): discrete_data = set(discrete_data) self.restore = tuple(sorted(discrete_data)) self.max_size = len(self.restore) self.size = 0 self.discrete_dict = dict(zip(self.restore, range(self.max_size))) self.bit = Fenwick(self.max_size + 1) self.nums = [False] * (self.max_size + 1) def __getitem__(self, index): return self.restore[self.bit.findkth(index % self.size + 1)] def add(self, val): if val not in self.discrete_dict: return val = self.discrete_dict[val] if val < 0 or val > self.max_size or self.nums[val]: return self.size += 1 self.bit.update(val, 1) self.nums[val] = True def discard(self, val): if val not in self.discrete_dict: return val = self.discrete_dict[val] if val < 0 or val > self.max_size or not self.nums[val]: return self.size -= 1 self.bit.update(val, -1) self.nums[val] = False def bisect_left(self, val): """ index of val """ return self.bit.query(self.discrete_dict[val]) def bisect_right(self, val): return self.bit.query(self.discrete_dict[val] + 1) def lower(self, val): index = self.bisect_left(val) if index == 0: return None return self[index - 1] def higher(self, val): index = self.bisect_right(val) if index == self.size: return None return self[index] def __delitem__(self, index): val = self.bit.findkth(index % self.size + 1) self.size -= 1 self.bit.update(val, -1) self.nums[val] = False def pop(self, index): val = self[index] del self[index] return val def __contains__(self, item): return self.nums[self.discrete_dict[item]] def __iter__(self): return (self.__getitem__(index) for index in range(self.size)) def __repr__(self): return 'Cset({})'.format(list(self)) def __len__(self): return self.size def __bool__(self): return self.size > 0 class RemovableHeap: def __init__(self, max_heap_type=None): if max_heap_type: # element's class class Transform(max_heap_type): def __lt__(self, other): return self >= other self._T = Transform else: self._T = lambda x: x self.heap = [] self.rem = [] self.dict = {} self.size = 0 def __len__(self): return self.size def __getitem__(self, index): self.__trim() return self.heap[index] def push(self, val): val = self._T(val) heappush(self.heap, val) if val in self.dict: self.dict[val] += 1 else: self.dict[val] = 1 self.size += 1 def pop(self): self.__trim() if not self.heap: return None self.size -= 1 val = heappop(self.heap) if self.dict[val] == 1: del self.dict[val] else: self.dict[val] -= 1 return val def remove(self, val): val = self._T(val) if val not in self.dict: return self.size -= 1 if self.dict[val] == 1: del self.dict[val] else: self.dict[val] -= 1 heappush(self.rem, val) def __trim(self): while self.rem and self.rem[0] == self.heap[0]: heappop(self.heap) heappop(self.rem) # ############################## main def solve(): n, q = mpint() arr = sorted(mpint()) discrete_data = arr.copy() input_data = [tuple(mpint()) for _ in range(q)] for t, x in input_data: if t == 1: discrete_data.append(x) discrete_data = set(discrete_data) indices = Cset(discrete_data) intervals = RemovableHeap(int) for a in arr: indices.add(a) for i in range(1, n): intervals.push(arr[i] - arr[i - 1]) def query(): if not intervals: return 0 return indices[-1] - indices[0] - intervals[0] print(query()) for t, x in input_data: if t == 0: # discard lower = indices.lower(x) higher = indices.higher(x) if lower: intervals.remove(x - lower) if higher: intervals.remove(higher - x) if lower and higher: intervals.push(higher - lower) indices.discard(x) else: # add lower = indices.lower(x) higher = indices.higher(x) if higher and lower: intervals.remove(higher - lower) if lower: intervals.push(x - lower) if higher: intervals.push(higher - x) indices.add(x) print(query()) if __name__ == '__main__': solve() # for _ in range(itg()): # print(solve()) # Please check! ```
instruction
0
56,569
8
113,138
Yes
output
1
56,569
8
113,139
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") import time start_time = time.time() import collections as col, math def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def solve(): # function to build the tree def build(arr) : # insert leaf nodes in tree for i in range(n) : x = arr[i] tree[n + i] = (counts[x],x,x,0); # build the tree by calculating parents for i in range(n - 1, 0, -1) : a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: if i << 1 == 2 and a[2] > b[2] and a[0] > 0: #gap missing gap to find is the difference between the max of the right tree and the element above it gap = tree2[1][1] - b[2] else: gap = b[1]-a[2] tree[i] = (a[0]+b[0],min(a[1],b[1]),max(a[2],b[2]),max(a[3],b[3],gap)); # function to update a tree node def updateTreeNode(p, value) : # set value at position p counts[p] = value #print(points_index[p]+n,len(points),len(tree)) #print(tree) tree[points_index[p] + n] = (value, p, p,0); # move upward and update parents i = points_index[p]+n; while i > 1 : #print(i) i >>= 1 #print(i,tree) a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: #if a[2] > b[2]: # gap = tree2[1][1] - b[2] #else: gap = b[1]-a[2] tree[i] = (a[0]+b[0],min(a[1],b[1]),max(a[2],b[2]),max(a[3],b[3],gap)); n, Q = getInts() P = getInts() queries = [] points = set(P) for q in range(Q): t, x = getInts() queries.append((t,x)) points.add(x) counts = col.defaultdict(int) for p in P: counts[p] = 1 points = sorted(list(points)) points_index = col.defaultdict(int) n = len(points) two_pow = 1 while two_pow <= 2*n: two_pow *= 2 n = two_pow//2 #add some dummy points j = 10**10 while len(points) < n: points.append(j+x) j += 1 tree = [0]*(two_pow) build(points) for i, point in enumerate(points): points_index[point] = i print(tree[1][2]-tree[1][1]-tree[1][3]) for t, x in queries: updateTreeNode(x,t) print(tree[1][2]-tree[1][1]-tree[1][3]) return #segment tree of counts #in each node, we store: the count (only ever 1 or 0), then minimum value, the maximum value #somehow need to come up with a way to store maxgap #the response to each query is max-min-maxgap solve() #print(time.time()-start_time) ```
instruction
0
56,570
8
113,140
Yes
output
1
56,570
8
113,141
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. Submitted Solution: ``` import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def get(t, l, r): l += len(t)//2 r += len(t)//2 res = -1 while l <= r: if l % 2 == 1: res = max(res, t[l]) if r % 2 == 0: res = max(res, t[r]) l = (l + 1) // 2 r = (r - 1) // 2 return res def change(t, x, v): x += len(t)//2 t[x] = v while x > 1: x //= 2 t[x] = max(t[x*2],t[x*2+1]) def build(t): for x in range(len(t)//2 - 1, 0, -1): t[x] = max(t[x*2],t[x*2+1]) def solve(): n, q = map(int,input().split()) p = list(map(int,input().split())) all_x = p[::] qe = [None]*q for i in range(q): t, x = map(int,input().split()) qe[i] = (t,x) all_x.append(x) all_x.append(0) all_x.append(int(1e9)+1) all_x.sort() id_x = dict() allx = [] idn = 0 for i in all_x: if i not in id_x: id_x[i] = idn idn += 1 allx.append(i) #print(allx) #print(id_x) m = idn nnext = [-1]*m pprev = [-1]*m z = [0]*m nnext[0] = m-1 pprev[m-1] = 0 have = [-1]*(m*2) have[m-1] = m-1 cnt = [0]*(m*2) build(have) change(have, 0, 0) build(cnt) for x in set(p): # add xi = id_x[x] pr = get(have, 0, xi) nz = x - allx[pr] change(cnt, pr, nz) change(have, xi, xi) ne = nnext[pr] change(cnt, xi, allx[ne] - x) nnext[pr] = xi nnext[xi] = ne pprev[xi] = pr pprev[ne] = xi #print(cnt[m:2*m]) #print(have[m:2*m]) #print(nnext) #print('===') if nnext[0] == m-1: print(0) # 0 piles else: ne = nnext[0] pr = pprev[m-1] if ne == pr: print(0) # single pile else: #print(ne,pr,get(cnt,ne,pr-1)) print(allx[pr]-allx[ne]-get(cnt,ne,pr-1)) for t, x in qe: xi = id_x[x] if t == 0: # remove ne = nnext[xi] pr = pprev[xi] change(have, xi, -1) change(cnt, xi, 0) change(cnt, pr, allx[ne]-allx[pr]) nnext[pr] = ne pprev[ne] = pr else: # add pr = get(have, 0, xi) nz = x - allx[pr] change(cnt, pr, nz) change(have, xi, xi) ne = nnext[pr] change(cnt, xi, allx[ne] - x) nnext[pr] = xi nnext[xi] = ne pprev[xi] = pr pprev[ne] = xi #print(cnt[m:2*m]) #print(have[m:2*m]) #print(nnext) #print('===') if nnext[0] == m-1: print(0) # 0 piles else: ne = nnext[0] pr = pprev[m-1] if ne == pr: print(0) # single pile else: #print(ne,pr,get(cnt,ne,pr-1)) print(allx[pr]-allx[ne]-get(cnt,ne,pr-1)) solve() ```
instruction
0
56,571
8
113,142
Yes
output
1
56,571
8
113,143
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") import time start_time = time.time() import collections as col, math def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def solve(): def build2(arr,tree,n): for i in range(n): x = arr[i] tree[n + i] = (counts[x],x) for i in range(n - 1, 0, -1) : a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: tree[i] = (a[0]+b[0],min(a[1],b[1])) def updateTreeNode2(p,value,tree,n): # set value at position p counts[p] = value #print(points_index[p]+n,len(points),len(tree)) #print(tree) tree[points_index[p]-len(points)+len(points2) + n] = (value, p) # move upward and update parents i = points_index[p]-len(points)+len(points2)+n; #print(tree) while i > 1 : #print(i) i >>= 1 #print(i,len(tree)) a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: tree[i] = (a[0]+b[0],min(a[1],b[1])) # function to build the tree def build(arr,tree,n,tree2) : # insert leaf nodes in tree for i in range(n) : x = arr[i] tree[n + i] = (counts[x],x,x,0); # build the tree by calculating parents for i in range(n - 1, 0, -1) : a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: if i << 1 == 2 and a[2] > b[2] and a[0] > 0: #gap missing gap to find is the difference between the max of the right tree and the element above it gap = tree2[1][1] - b[2] else: gap = b[1]-a[2] tree[i] = (a[0]+b[0],min(a[1],b[1]),max(a[2],b[2]),max(a[3],b[3],gap)); # function to update a tree node def updateTreeNode(p, value, tree, n, tree2) : # set value at position p counts[p] = value #print(points_index[p]+n,len(points),len(tree)) #print(tree) tree[points_index[p] + n] = (value, p, p,0); # move upward and update parents i = points_index[p]+n; while i > 1 : #print(i) i >>= 1 #print(i,len(tree)) a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: if i == 1 and a[2] > b[2] and a[0] > 0: gap = tree2[1][1] - b[2] else: gap = b[1]-a[2] tree[i] = (a[0]+b[0],min(a[1],b[1]),max(a[2],b[2]),max(a[3],b[3],gap)); n, Q = getInts() P = getInts() queries = [] points = set(P) for q in range(Q): t, x = getInts() queries.append((t,x)) points.add(x) counts = col.defaultdict(int) for p in P: counts[p] = 1 points = sorted(list(points)) points_index = col.defaultdict(int) n = len(points) tree = [0]*(2*n) #for cases where n is not a power of two, I need to include one additional gap: the gap from the minimum value of the final layer, and the max value #of the previous layer #I can have a second seg tree just to find the minimum of these values #how many values are there? ans = 2*n - highest power of two below two_pow = 1 while two_pow*2 <= 2*n: two_pow *= 2 if two_pow == 2*n: tree2 = [] else: tree2 = [0]*(2*n-two_pow) for i, point in enumerate(points): points_index[point] = i n2 = 2*n-two_pow points2 = points[-n2:] #print(points2) tree2 = [0]*(2*n2) if n2: build2(points2,tree2,n2) #print(tree2) build(points,tree,n,tree2) points2_set = set(points2) print(tree[1][2]-tree[1][1]-tree[1][3]) for t, x in queries: if x in points2: updateTreeNode2(x,t,tree2,n2) updateTreeNode(x,t,tree,n,tree2) #print(tree) print(tree[1][2]-tree[1][1]-tree[1][3]) return #segment tree of counts #in each node, we store: the count (only ever 1 or 0), then minimum value, the maximum value #somehow need to come up with a way to store maxgap #the response to each query is max-min-maxgap solve() #print(time.time()-start_time) ```
instruction
0
56,572
8
113,144
No
output
1
56,572
8
113,145
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. Submitted Solution: ``` n, q = map(int, input().split()) p = list(map(int, input().split())) p.sort() r = p[n - 1] l = p[0] ans = p[n - 1] - p[1] for i in range(2, n): if p[i - 1] - p[0] + p[n - 1] - p[i] < ans: ans = p[i - 1] - p[0] + p[n - 1] - p[i] print(ans) j = 0 while j < q: d, x = map(int, input().split()) if d == 0: for i in range(n): if p[i] == x: p.pop(i) n -= 1 break if len(p) <= 2: print(0) j += 1 else: ans = p[n - 1] - p[1] for i in range(2, n): if p[i - 1] - p[0] + p[n - 1] - p[i] < ans: ans = p[i - 1] - p[0] + p[n - 1] - p[i] print(ans) j += 1 else: if p == []: p.append(x) n += 1 j += 1 elif x < p[0]: p = [x] + p n += 1 ans = p[n - 1] - p[1] for i in range(2, n): if p[i - 1] - p[0] + p[n - 1] - p[i] < ans: ans = p[i - 1] - p[0] + p[n - 1] - p[i] print(ans) j += 1 elif x > p[n - 1]: p = p + [x] n += 1 ans = p[n - 1] - p[1] for i in range(2, n): if p[i - 1] - p[0] + p[n - 1] - p[i] < ans: ans = p[i - 1] - p[0] + p[n - 1] - p[i] print(ans) j += 1 else: for i in range(n): if p[i] < x and x < p[i + 1]: p.insert(i + 1, x) n += 1 ans = p[n - 1] - p[1] for i in range(2, n): if p[i - 1] - p[0] + p[n - 1] - p[i] < ans: ans = p[i - 1] - p[0] + p[n - 1] - p[i] print(ans) j += 1 ```
instruction
0
56,573
8
113,146
No
output
1
56,573
8
113,147
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. Submitted Solution: ``` def evaluate(p_s, deltas): if(len(p_s)<=2): return 0 return (p_s[-1]-p_s[0]) - max(deltas) def execute(t, x, p_s, deltas): if t: for i in range(len(p_s)): if p_s[i]>x: deltas[i] = p_s[i] - x deltas.insert(i,(x-p_s[i-1]) if i != 0 else 0) p_s.insert(i,x) return deltas.append(x-p_s[-1] if len(p_s)!=0 else 0) p_s.append(x) else: ind = p_s.index(x) del p_s[ind] if len(deltas)-1!= ind: deltas[ind+1] += deltas[ind] if ind == 0 and len(p_s)>1: deltas[1] = 0 del deltas[ind] n,q = map(int, input().split()) p_s = list(map(int, input().split())) p_s.sort() q_s = [] deltas = [0]+[p_s[i] - p_s[i-1] for i in range(1,len(p_s)) ] print(evaluate(p_s, deltas)) for _ in range(q): q_s = tuple(map(int, input().split())) execute(*q_s, p_s, deltas) #print(p_s,deltas) print(evaluate(p_s, deltas)) ```
instruction
0
56,574
8
113,148
No
output
1
56,574
8
113,149
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates. Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move. Also, there are two types of queries: * 0 x β€” remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment. * 1 x β€” add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment. Note that it is possible that there are zero piles of trash in the room at some moment. Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves. For better understanding, please read the Notes section below to see an explanation for the first example. Input The first line of the input contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ 10^9), where p_i is the coordinate of the i-th pile. The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 ≀ t_i ≀ 1; 1 ≀ x_i ≀ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles. Output Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries. Examples Input 5 6 1 2 6 8 10 1 4 1 9 0 6 0 10 1 100 1 50 Output 5 7 7 5 4 8 49 Input 5 8 5 1 2 4 3 0 1 0 2 0 3 0 4 0 5 1 1000000000 1 1 1 500000000 Output 3 2 1 0 0 0 0 0 499999999 Note Consider the first example. Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves. After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves. After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles). After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move. After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10). After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8. After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") import time start_time = time.time() import collections as col, math def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def solve(): def build2(arr,tree,n): for i in range(n): x = arr[i] tree[n + i] = (counts[x],x) for i in range(n - 1, 0, -1) : a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: tree[i] = (a[0]+b[0],min(a[1],b[1])) def updateTreeNode2(p,value,tree,n): # set value at position p counts[p] = value #print(points_index[p]+n,len(points),len(tree)) #print(tree) tree[points_index[p]-len(points)+len(points2) + n] = (value, p) # move upward and update parents i = points_index[p]-len(points)+len(points2)+n; #print(tree) while i > 1 : #print(i) i >>= 1 #print(i,len(tree)) a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: tree[i] = (a[0]+b[0],min(a[1],b[1])) # function to build the tree def build(arr,tree,n,tree2) : # insert leaf nodes in tree for i in range(n) : x = arr[i] tree[n + i] = (counts[x],x,x,0); # build the tree by calculating parents for i in range(n - 1, 0, -1) : a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: if i << 1 == 2 and a[2] > b[2] and a[0] > 0: #gap missing gap to find is the difference between the max of the right tree and the element above it gap = tree2[1][1] - b[2] else: gap = b[1]-a[2] tree[i] = (a[0]+b[0],min(a[1],b[1]),max(a[2],b[2]),max(a[3],b[3],gap)); # function to update a tree node def updateTreeNode(p, value, tree, n, tree2) : # set value at position p counts[p] = value #print(points_index[p]+n,len(points),len(tree)) #print(tree) tree[points_index[p] + n] = (value, p, p,0); # move upward and update parents i = points_index[p]+n; while i > 1 : #print(i) i >>= 1 #print(i,tree) a, b = tree[i << 1], tree[i << 1 | 1] if a[0] == 0: tree[i] = b elif b[0] == 0: tree[i] = a else: if a[2] > b[2] and a[0] > 0: gap = tree2[1][1] - b[2] else: gap = b[1]-a[2] tree[i] = (a[0]+b[0],min(a[1],b[1]),max(a[2],b[2]),max(a[3],b[3],gap)); n, Q = getInts() P = getInts() queries = [] points = set(P) for q in range(Q): t, x = getInts() queries.append((t,x)) points.add(x) counts = col.defaultdict(int) for p in P: counts[p] = 1 points = sorted(list(points)) points_index = col.defaultdict(int) n = len(points) tree = [0]*(2*n) #for cases where n is not a power of two, I need to include one additional gap: the gap from the minimum value of the final layer, and the max value #of the previous layer #I can have a second seg tree just to find the minimum of these values #how many values are there? ans = 2*n - highest power of two below two_pow = 1 while two_pow*2 <= 2*n: two_pow *= 2 if two_pow == 2*n: tree2 = [] else: tree2 = [0]*(2*n-two_pow) for i, point in enumerate(points): points_index[point] = i n2 = 2*n-two_pow points2 = points[-n2:] #print(points2) tree2 = [0]*(2*n2) if n2: build2(points2,tree2,n2) #print(tree2) build(points,tree,n,tree2) points2_set = set(points2) print(tree[1][2]-tree[1][1]-tree[1][3]) for t, x in queries: if x in points2: updateTreeNode2(x,t,tree2,n2) updateTreeNode(x,t,tree,n,tree2) #print(tree) print(tree[1][2]-tree[1][1]-tree[1][3]) return #segment tree of counts #in each node, we store: the count (only ever 1 or 0), then minimum value, the maximum value #somehow need to come up with a way to store maxgap #the response to each query is max-min-maxgap solve() #print(time.time()-start_time) ```
instruction
0
56,575
8
113,150
No
output
1
56,575
8
113,151
Provide tags and a correct Python 3 solution for this coding contest problem. You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. Input First line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 ≀ x_i, y_i ≀ 10^9). It's guaranteed that the sum of all n does not exceed 1000. Output For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house. Example Input 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 Note Here are the images for the example test cases. Blue dots stand for the houses, green β€” possible positions for the exhibition. <image> First test case. <image> Second test case. <image> Third test case. <image> Fourth test case. <image> Fifth test case. <image> Sixth test case. Here both houses are located at (0, 0).
instruction
0
56,608
8
113,216
Tags: binary search, geometry, shortest paths, sortings Correct Solution: ``` def main(): T = int(input()) for _ in range(T): n = input().strip() n = int(n) x = [0 for i in range(n)] y = [0 for i in range(n)] for i in range(n): p, q = map(int, input().split()) x[i] = p y[i] = q x = sorted(x) y = sorted(y) sx = sum(x) sy = sum(y) ax = sx / n ay = sy / n wx = x[n // 2] wy = y[n // 2] ux = 2 * sx uy = 2 * sy wx *= n wy *= n # print(_, sx/n, sy/n, wx/n, wy/n) # print(ux,uy,sx,sy,wx,wy) if n % 2 == 1: print("1") else: print((x[n // 2] - x[n // 2 - 1] + 1) * (y[n // 2] - y[n // 2 - 1] + 1)) # if sx == wx and sy == wy: # print("1") # elif sx == wx: # if n % 2 == 1: # print("1") # else: # print(y[n // 2] - y[n // 2 - 1] + 1) # # elif sy == wy: # if n % 2 == 1: # print("1") # else: # print(x[n // 2] - x[n // 2 - 1] + 1) # else: # ans = 1 # # print(_, ux, uy, wx, wy) # if wx*2 != ux: # ans *= 2 # if wy*2 != uy: # ans *= 2 # print(ans) # if sx%n!=0 or sy%n!=0: # print("1") # else: # pass # x_sum = [0 for i in range(n)] # y_sum = [0 for i in range(n)] # region fastio import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
output
1
56,608
8
113,217
Provide tags and a correct Python 3 solution for this coding contest problem. You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. Input First line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 ≀ x_i, y_i ≀ 10^9). It's guaranteed that the sum of all n does not exceed 1000. Output For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house. Example Input 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 Note Here are the images for the example test cases. Blue dots stand for the houses, green β€” possible positions for the exhibition. <image> First test case. <image> Second test case. <image> Third test case. <image> Fourth test case. <image> Fifth test case. <image> Sixth test case. Here both houses are located at (0, 0).
instruction
0
56,609
8
113,218
Tags: binary search, geometry, shortest paths, sortings Correct Solution: ``` #from sys import stdin,stdout #input=stdin.readline #from itertools import permutations from collections import Counter #import collections #import heapq #from collections import deque import math #dx=[-1,1,0,0] #dy=[0,0,-1,1] #dx=[1,-1,-1,1] #dy=[-1,-1,1,1] for _ in range(int(input())): n=int(input()) lx,ly=[],[] for i in range(n): x,y=map(int,input().split()) lx.append(x) ly.append(y) if n%2==1: print(1) continue lx.sort() ly.sort() d1=lx[(n)//2]-lx[(n-1)//2]+1 d2=ly[(n)//2]-ly[(n-1)//2]+1 print(d1*d2) ```
output
1
56,609
8
113,219
Provide tags and a correct Python 3 solution for this coding contest problem. You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. Input First line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 ≀ x_i, y_i ≀ 10^9). It's guaranteed that the sum of all n does not exceed 1000. Output For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house. Example Input 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 Note Here are the images for the example test cases. Blue dots stand for the houses, green β€” possible positions for the exhibition. <image> First test case. <image> Second test case. <image> Third test case. <image> Fourth test case. <image> Fifth test case. <image> Sixth test case. Here both houses are located at (0, 0).
instruction
0
56,610
8
113,220
Tags: binary search, geometry, shortest paths, sortings Correct Solution: ``` mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.buffer.readline for _ in range(int(input())): X = [] Y = [] N = int(input()) for _ in range(N): x, y = map(int, input().split()) X.append(x) Y.append(y) X.sort() Y.sort() if N & 1: print(1) else: print((X[N // 2] - X[(N // 2) - 1] + 1) * (Y[N // 2] - Y[(N // 2) - 1] + 1)) if __name__ == '__main__': main() ```
output
1
56,610
8
113,221
Provide tags and a correct Python 3 solution for this coding contest problem. You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. Input First line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 ≀ x_i, y_i ≀ 10^9). It's guaranteed that the sum of all n does not exceed 1000. Output For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house. Example Input 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 Note Here are the images for the example test cases. Blue dots stand for the houses, green β€” possible positions for the exhibition. <image> First test case. <image> Second test case. <image> Third test case. <image> Fourth test case. <image> Fifth test case. <image> Sixth test case. Here both houses are located at (0, 0).
instruction
0
56,611
8
113,222
Tags: binary search, geometry, shortest paths, sortings Correct Solution: ``` from math import ceil,floor,log import sys from heapq import heappush,heappop from collections import Counter,defaultdict,deque input=lambda : sys.stdin.readline().strip() c=lambda x: 10**9 if(x=="?") else int(x) class node: def __init__(self,x,y): self.a=[x,y] def __lt__(self,b): return b.a[0]<self.a[0] def __repr__(self): return str(self.a[0])+" "+str(self.a[1]) def main(): for _ in range(int(input())): n=int(input()) a,b=zip(*[list(map(int,input().split())) for i in range(n)]) a=list(a) b=list(b) if(n%2==1): print(1) else: a.sort() b.sort() print(max((b[n//2-1]-b[n//2]-1)*(a[n//2-1]-a[n//2]-1),0)) main() ```
output
1
56,611
8
113,223
Provide tags and a correct Python 3 solution for this coding contest problem. You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. Input First line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 ≀ x_i, y_i ≀ 10^9). It's guaranteed that the sum of all n does not exceed 1000. Output For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house. Example Input 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 Note Here are the images for the example test cases. Blue dots stand for the houses, green β€” possible positions for the exhibition. <image> First test case. <image> Second test case. <image> Third test case. <image> Fourth test case. <image> Fifth test case. <image> Sixth test case. Here both houses are located at (0, 0).
instruction
0
56,612
8
113,224
Tags: binary search, geometry, shortest paths, sortings Correct Solution: ``` from sys import stdin input = stdin.readline for _ in range(int(input())): n = int(input()) hx = [] hy = [] for _ in range(n): x, y = map(int, input().split()) hx.append(x) hy.append(y) hx.sort() hy.sort() if n % 2 == 1: print(1) #print(hx[n // 2], hy[n // 2]) #print("===") else: print((hx[n // 2] - hx[n // 2 -1] +1) * (hy[n// 2 ] - hy[n// 2 - 1] + 1)) #print("===") ```
output
1
56,612
8
113,225
Provide tags and a correct Python 3 solution for this coding contest problem. You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. Input First line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 ≀ x_i, y_i ≀ 10^9). It's guaranteed that the sum of all n does not exceed 1000. Output For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house. Example Input 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 Note Here are the images for the example test cases. Blue dots stand for the houses, green β€” possible positions for the exhibition. <image> First test case. <image> Second test case. <image> Third test case. <image> Fourth test case. <image> Fifth test case. <image> Sixth test case. Here both houses are located at (0, 0).
instruction
0
56,614
8
113,228
Tags: binary search, geometry, shortest paths, sortings Correct Solution: ``` import os DEBUG = 'DEBUG' in os.environ def debug(*args): if DEBUG: print(">", *args) def solution(houses): if len(houses) == 1: return 1 housesX = [] housesY = [] for house in houses: housesX.append(house[0]) housesY.append(house[1]) housesX.sort() housesY.sort() leftX = -1 rightX = -1 topY = -1 bottomY = -1 # if even # 0 1 2 3 if len(houses) % 2 == 0: leftX = housesX[len(houses) // 2 - 1] rightX = housesX[len(houses) // 2] bottomY = housesY[len(houses) // 2 - 1] topY = housesY[len(houses) // 2] return (rightX - leftX + 1) * (topY - bottomY + 1) # if odd # 0 1 2 if len(houses) % 2 == 1: return 1 debug(leftX, rightX, topY, bottomY) return "NO" for t in range(int(input())): houses = [] for t2 in range(int(input())): houses.append(list(map(int, input().split()))) print(solution(houses)) ```
output
1
56,614
8
113,229
Provide tags and a correct Python 3 solution for this coding contest problem. You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. Input First line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 ≀ x_i, y_i ≀ 10^9). It's guaranteed that the sum of all n does not exceed 1000. Output For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house. Example Input 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 Note Here are the images for the example test cases. Blue dots stand for the houses, green β€” possible positions for the exhibition. <image> First test case. <image> Second test case. <image> Third test case. <image> Fourth test case. <image> Fifth test case. <image> Sixth test case. Here both houses are located at (0, 0).
instruction
0
56,615
8
113,230
Tags: binary search, geometry, shortest paths, sortings Correct Solution: ``` a = int(input()) for x in range(a): b = int(input()) h = [] m = [] for y in range(b): d,e = map(int,input().split()) h.append(d) m.append(e) h.sort() m.sort() if b&1 == 1: print(1) else: print((h[b//2]-h[b//2 - 1] + 1) * (m[b//2] -m[b//2 - 1] + 1)) ```
output
1
56,615
8
113,231
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x. Input First line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 ≀ x_i, y_i ≀ 10^9). It's guaranteed that the sum of all n does not exceed 1000. Output For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house. Example Input 6 3 0 0 2 0 1 2 4 1 0 0 2 2 3 3 1 4 0 0 0 1 1 0 1 1 2 0 0 1 1 2 0 0 2 0 2 0 0 0 0 Output 1 4 4 4 3 1 Note Here are the images for the example test cases. Blue dots stand for the houses, green β€” possible positions for the exhibition. <image> First test case. <image> Second test case. <image> Third test case. <image> Fourth test case. <image> Fifth test case. <image> Sixth test case. Here both houses are located at (0, 0). Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def S(): return input().strip() def print_list(l): print(' '.join(map(str, l))) # sys.setrecursionlimit(100000) # import random # from functools import reduce # from functools import lru_cache # from heapq import * # from collections import deque as dq # import math # import bisect as bs # from collections import Counter # from collections import defaultdict as dc for _ in range(N()): x, y, n = [], [], N() if n & 1: for _ in range(n): input() print(1) continue for _ in range(n): a, b = RL() x.append(a) y.append(b) x.sort() y.sort() k = n >> 1 print((x[k] - x[k - 1] + 1) * (y[k] - y[k - 1] + 1)) ```
instruction
0
56,616
8
113,232
Yes
output
1
56,616
8
113,233
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has d buttons with digits from 0 to d - 1. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a "RESET" button β€” pressing it pops up all other buttons. Initially, no buttons are pushed down. The door instantly opens when some specific set of digits is pushed down. Sadly, you don't know the password for it. Having read the documentation for this specific lock, you found out that there are n possible passwords for this particular lock. Find the shortest sequence of button presses, such that all possible passwords appear at least once during its execution. Any shortest correct sequence of button presses will be accepted. Input The first line contains two integers d and n (1 ≀ d ≀ 10; 1 ≀ n ≀ 2^d - 1). Next n lines describe possible passwords. Each line contains a string s_i of d zeros and ones: for all j from 1 to d the j-th character is 1 iff the button with the digit j - 1 must be pushed down. All strings s_i are different, and each string contains at least one 1. Output On the first line, print the number k β€” the minimum number of button presses. On the second line, print k tokens, describing the sequence. Whenever you press a button with a digit, print that digit. Whenever you press "RESET", print "R". Examples Input 2 2 10 11 Output 2 0 1 Input 3 4 001 111 101 011 Output 6 2 0 R 1 2 0 Note In the second example, the sequence 1 2 R 2 0 1 is also possible. Submitted Solution: ``` d, n = map(int, input().split()) has = set() word = sorted([input()for _ in range(n)], key=lambda x: x.count('1')) g = [[]for _ in range(n)] nxt = [-1]*n vis = [0]*n def connect(a, b): for p in range(d): if a[p] == '1' and b[p] == '0': return False return True for i in range(n): for j in range(i-1, -1, -1): if connect(word[j], word[i]): g[i].append(j) for i in range(n): def change_to(): for j in g[i]: if nxt[j] == -1: nxt[j] = i return for k in g[nxt[j]]: if nxt[k] == -1: nxt[k] = nxt[j] nxt[j] = i return change_to() ans = [] # print(g) # print(nxt) def circle(start): res = [] def reach(a, b): # print(a, b) for p in range(d): if a[p] == '0' and b[p] == '1': res.append(p) reach('0'*d, word[start]) # print(res) cur = start while nxt[cur] != -1: reach(word[cur], word[nxt[cur]]) cur = nxt[cur] vis[cur] = 1 # print(res) ans.append(' '.join(map(str, res))) for i in range(n): if not vis[i]: circle(i) out = ' R '.join(ans) print(len(out.split())) print(out) ```
instruction
0
56,624
8
113,248
No
output
1
56,624
8
113,249
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has d buttons with digits from 0 to d - 1. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a "RESET" button β€” pressing it pops up all other buttons. Initially, no buttons are pushed down. The door instantly opens when some specific set of digits is pushed down. Sadly, you don't know the password for it. Having read the documentation for this specific lock, you found out that there are n possible passwords for this particular lock. Find the shortest sequence of button presses, such that all possible passwords appear at least once during its execution. Any shortest correct sequence of button presses will be accepted. Input The first line contains two integers d and n (1 ≀ d ≀ 10; 1 ≀ n ≀ 2^d - 1). Next n lines describe possible passwords. Each line contains a string s_i of d zeros and ones: for all j from 1 to d the j-th character is 1 iff the button with the digit j - 1 must be pushed down. All strings s_i are different, and each string contains at least one 1. Output On the first line, print the number k β€” the minimum number of button presses. On the second line, print k tokens, describing the sequence. Whenever you press a button with a digit, print that digit. Whenever you press "RESET", print "R". Examples Input 2 2 10 11 Output 2 0 1 Input 3 4 001 111 101 011 Output 6 2 0 R 1 2 0 Note In the second example, the sequence 1 2 R 2 0 1 is also possible. Submitted Solution: ``` import os, sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from math import sqrt,ceil,gcd from _collections import deque m,n=map(int,input().split()) a=[input() for _ in range(n)] d=dict() z=dict() for i,vl in enumerate(a): for j,v in enumerate(vl): if v=='1': d[j]=d.get(j,0)+1 z[vl]=z.get(vl,[]) z[vl].append(j) ans=[] print(d,z) while d: ck=[] for i in d: ck.append([d[i],i]) ck.sort(reverse=True) c=[] for i,j in ck: c.append(j) check=set() g=['0']*m for i in c: g[i]='1' gk=str() for i in g: gk+=i check.add(gk) #print(check,z) for i in check: if i in z: for j in z[i]: d[j]-=1 #print(i) z[i].clear() for i in range(m): if i in d and not d[i]: d.__delitem__(i) for i in c: ans.append(i) if d: ans.append('R') print(len(ans)) print(*ans) ```
instruction
0
56,625
8
113,250
No
output
1
56,625
8
113,251
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has d buttons with digits from 0 to d - 1. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a "RESET" button β€” pressing it pops up all other buttons. Initially, no buttons are pushed down. The door instantly opens when some specific set of digits is pushed down. Sadly, you don't know the password for it. Having read the documentation for this specific lock, you found out that there are n possible passwords for this particular lock. Find the shortest sequence of button presses, such that all possible passwords appear at least once during its execution. Any shortest correct sequence of button presses will be accepted. Input The first line contains two integers d and n (1 ≀ d ≀ 10; 1 ≀ n ≀ 2^d - 1). Next n lines describe possible passwords. Each line contains a string s_i of d zeros and ones: for all j from 1 to d the j-th character is 1 iff the button with the digit j - 1 must be pushed down. All strings s_i are different, and each string contains at least one 1. Output On the first line, print the number k β€” the minimum number of button presses. On the second line, print k tokens, describing the sequence. Whenever you press a button with a digit, print that digit. Whenever you press "RESET", print "R". Examples Input 2 2 10 11 Output 2 0 1 Input 3 4 001 111 101 011 Output 6 2 0 R 1 2 0 Note In the second example, the sequence 1 2 R 2 0 1 is also possible. Submitted Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip("\r\n") from math import sqrt,ceil,gcd from _collections import deque m,n=map(int,input().split()) a=[input() for _ in range(n)] d=dict() for i in a: for j,v in enumerate(i): if v=='1': d[j]=d.get(j,set()) d[j].add(i) ans=[] #print(d) while d: ck=[] for i in d: ck.append([len(d[i]),i]) ck.sort(reverse=True) c=[] for i,j in ck: c.append(j) check=set() g=['0']*m for i in c: g[i]='1' gk=str() for i in g: gk+=i check.add(gk) # print(check) for i in d : tot=set() for j in d[i]: if j in check: tot.add(j) for j in tot: d[i].remove(j) for i in range(m): if i in d and not d[i]: d.__delitem__(i) for i in c: ans.append(i) if d: ans.append('R') print(*ans) ```
instruction
0
56,626
8
113,252
No
output
1
56,626
8
113,253
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has d buttons with digits from 0 to d - 1. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a "RESET" button β€” pressing it pops up all other buttons. Initially, no buttons are pushed down. The door instantly opens when some specific set of digits is pushed down. Sadly, you don't know the password for it. Having read the documentation for this specific lock, you found out that there are n possible passwords for this particular lock. Find the shortest sequence of button presses, such that all possible passwords appear at least once during its execution. Any shortest correct sequence of button presses will be accepted. Input The first line contains two integers d and n (1 ≀ d ≀ 10; 1 ≀ n ≀ 2^d - 1). Next n lines describe possible passwords. Each line contains a string s_i of d zeros and ones: for all j from 1 to d the j-th character is 1 iff the button with the digit j - 1 must be pushed down. All strings s_i are different, and each string contains at least one 1. Output On the first line, print the number k β€” the minimum number of button presses. On the second line, print k tokens, describing the sequence. Whenever you press a button with a digit, print that digit. Whenever you press "RESET", print "R". Examples Input 2 2 10 11 Output 2 0 1 Input 3 4 001 111 101 011 Output 6 2 0 R 1 2 0 Note In the second example, the sequence 1 2 R 2 0 1 is also possible. Submitted Solution: ``` import math # inputs LockInfo = input() size = int(LockInfo[0]) SolutionNum = int(LockInfo[2]) # create keys for dict AllSolutions = {} for x in range(size + 1): AllSolutions.update({x: []}) # log values in dict for x in range(SolutionNum): sol = input() KeyNum = 0 for y in range(len(sol)): if sol[y] == '1': KeyNum += 1 AllSolutions[KeyNum].append(sol) print(AllSolutions) # Create final order Ordered = [] DictEmpty = False EmptyKeys = 0 # Loop while dict has something in it while EmptyKeys < len(AllSolutions): EmptyKeys = 0 # Loop through dict & log keys for x in range(len(AllSolutions)): if AllSolutions[x]: Ordered.append(AllSolutions[x].pop(0)) else: EmptyKeys += 1 print(Ordered) # Convert to button presses Ordered2 = [] FinalOrder = [] for x in range(len(Ordered)): if x % size != 0: SplitStr = list(map(str, Ordered[x])) for y in range(size): SplitStr[y] = str(int(Ordered[x][y]) - int(Ordered[x-1][y])) Ordered2.append(''.join(SplitStr)) else: Ordered2.append(Ordered[x]) button = 0 for y in range(size): if(Ordered2[x][y]) == '1': FinalOrder.append(button) button += 1 else: button += 1 # insert resets for x in range(math.floor(len(FinalOrder) / size)): if (x+1) * size != len(FinalOrder): FinalOrder.insert((x+1) * size, 'R') print(len(FinalOrder)) print(' '.join(map(str, FinalOrder))) ```
instruction
0
56,627
8
113,254
No
output
1
56,627
8
113,255
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that? Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of disks on the combination lock. The second line contains a string of n digits β€” the original state of the disks. The third line contains a string of n digits β€” Scrooge McDuck's combination that opens the lock. Output Print a single integer β€” the minimum number of moves Scrooge McDuck needs to open the lock. Examples Input 5 82195 64723 Output 13 Note In the sample he needs 13 moves: * 1 disk: <image> * 2 disk: <image> * 3 disk: <image> * 4 disk: <image> * 5 disk: <image> Submitted Solution: ``` n = int(input()) ori = list(map(int,list(input()))) target = list(map(int,list(input()))) ans = 0 for i in range(n): diff = abs(ori[i]-target[i]) if diff>5: ans+=10-diff else: ans+=diff print(ans) ```
instruction
0
56,719
8
113,438
Yes
output
1
56,719
8
113,439
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that? Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of disks on the combination lock. The second line contains a string of n digits β€” the original state of the disks. The third line contains a string of n digits β€” Scrooge McDuck's combination that opens the lock. Output Print a single integer β€” the minimum number of moves Scrooge McDuck needs to open the lock. Examples Input 5 82195 64723 Output 13 Note In the sample he needs 13 moves: * 1 disk: <image> * 2 disk: <image> * 3 disk: <image> * 4 disk: <image> * 5 disk: <image> Submitted Solution: ``` n = int(input()) start = list(input()) end = list(input()) total = 0 for i in range(0, n): d = int(start[i]) - int(end[i]) if d < -5: total += 10 + d elif d < 0: total += -d elif d < 5: total += d else: total += 10 - d print(total) ```
instruction
0
56,720
8
113,440
Yes
output
1
56,720
8
113,441
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that? Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of disks on the combination lock. The second line contains a string of n digits β€” the original state of the disks. The third line contains a string of n digits β€” Scrooge McDuck's combination that opens the lock. Output Print a single integer β€” the minimum number of moves Scrooge McDuck needs to open the lock. Examples Input 5 82195 64723 Output 13 Note In the sample he needs 13 moves: * 1 disk: <image> * 2 disk: <image> * 3 disk: <image> * 4 disk: <image> * 5 disk: <image> Submitted Solution: ``` a=int(input()) b=input() c=input() d=[0,1,2,3,4,5,6,7,8,9] k=[] for i in range(0,a): m=int(b[i])-int(c[i]) if(abs(int(b[i])-int(c[i]))>5): m=10-(abs(int(b[i])-int(c[i]))) k.append(m) f=0 for i in k: f=f+abs(i) print(f) ```
instruction
0
56,721
8
113,442
Yes
output
1
56,721
8
113,443
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that? Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of disks on the combination lock. The second line contains a string of n digits β€” the original state of the disks. The third line contains a string of n digits β€” Scrooge McDuck's combination that opens the lock. Output Print a single integer β€” the minimum number of moves Scrooge McDuck needs to open the lock. Examples Input 5 82195 64723 Output 13 Note In the sample he needs 13 moves: * 1 disk: <image> * 2 disk: <image> * 3 disk: <image> * 4 disk: <image> * 5 disk: <image> Submitted Solution: ``` n= int(input()) o=[int(i) for i in input()] c = [int(i) for i in input()] summ = 0 for i in range(n): diff = abs(o[i] - c[i]) if diff > 5: ten = 10 - diff turn = ten else: turn = diff summ = summ + turn print(summ) ```
instruction
0
56,722
8
113,444
Yes
output
1
56,722
8
113,445
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that? Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of disks on the combination lock. The second line contains a string of n digits β€” the original state of the disks. The third line contains a string of n digits β€” Scrooge McDuck's combination that opens the lock. Output Print a single integer β€” the minimum number of moves Scrooge McDuck needs to open the lock. Examples Input 5 82195 64723 Output 13 Note In the sample he needs 13 moves: * 1 disk: <image> * 2 disk: <image> * 3 disk: <image> * 4 disk: <image> * 5 disk: <image> Submitted Solution: ``` digit = int(input("Enter the number of digits: ")) originalState = input("Enter the original state: ") combination = input("Enter the combination: ") diffl = [] ol = [x for x in originalState] cl = [y for y in combination] for i in range(len(ol)): diff = abs(int(ol[i])-int(cl[i])) if diff>5: diffl.append(10-diff) else: diffl.append(diff) summ = 0 for l in diffl: summ += l print(summ) ```
instruction
0
56,723
8
113,446
No
output
1
56,723
8
113,447
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that? Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of disks on the combination lock. The second line contains a string of n digits β€” the original state of the disks. The third line contains a string of n digits β€” Scrooge McDuck's combination that opens the lock. Output Print a single integer β€” the minimum number of moves Scrooge McDuck needs to open the lock. Examples Input 5 82195 64723 Output 13 Note In the sample he needs 13 moves: * 1 disk: <image> * 2 disk: <image> * 3 disk: <image> * 4 disk: <image> * 5 disk: <image> Submitted Solution: ``` n=int(input()) a=input() b=input() c=0 for i in range(5): x=min(abs(int(a[i])-int(b[i])),10-abs(int(a[i])-int(b[i]))) c+=x print(c) ```
instruction
0
56,725
8
113,450
No
output
1
56,725
8
113,451
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that? Input The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of disks on the combination lock. The second line contains a string of n digits β€” the original state of the disks. The third line contains a string of n digits β€” Scrooge McDuck's combination that opens the lock. Output Print a single integer β€” the minimum number of moves Scrooge McDuck needs to open the lock. Examples Input 5 82195 64723 Output 13 Note In the sample he needs 13 moves: * 1 disk: <image> * 2 disk: <image> * 3 disk: <image> * 4 disk: <image> * 5 disk: <image> Submitted Solution: ``` a=int(input("")) x=int(input("")) y=int(input("")) b=0 c=0 count=0 temp1=0 temp2=0 temp=0 while(x>0 and y>0): b=x%10 c=y%10 if b>=c: temp=int(b)-int(c) temp1=10-int(b)+int(c) if(temp<temp1): count=count+temp #print(count) else: count=count+temp1 #print(count) else: temp=int(c)-int(b) temp2=10-int(c)+int(b) if(temp<temp2): count=count+temp #print(count) else: count=count+temp2 #print(count) x=(x-b)/10 y=(y-c)/10 if(x==0 and y>0): count=count+int(y)-int(x) elif(y==0 and x>0): count=count+int(x)-int(y) print(count) ```
instruction
0
56,726
8
113,452
No
output
1
56,726
8
113,453
Provide tags and a correct Python 3 solution for this coding contest problem. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1.
instruction
0
56,882
8
113,764
Tags: dsu, greedy, implementation, trees Correct Solution: ``` print(int(input()) + 1 - len(set(map(int, input().split())))) ```
output
1
56,882
8
113,765
Provide tags and a correct Python 3 solution for this coding contest problem. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1.
instruction
0
56,883
8
113,766
Tags: dsu, greedy, implementation, trees Correct Solution: ``` n = int(input()) t = list(map(int, input().split(' '))) a = [0] h = 1 cur_t = 1 d = {0:0} for ti in t: if d[a[ti]] != ti: a.append(h) d[h] = cur_t h += 1 else: d[a[ti]] = cur_t a.append(a[ti]) cur_t += 1 print (h) ```
output
1
56,883
8
113,767
Provide tags and a correct Python 3 solution for this coding contest problem. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1.
instruction
0
56,884
8
113,768
Tags: dsu, greedy, implementation, trees Correct Solution: ``` n = int(input()) A = list(map(int, input().split())) D = {} for i in range (n): D[A[i]] = D.get ( A[i], -1 ) + 1 a = sum(D.values())+1 print(a) ```
output
1
56,884
8
113,769
Provide tags and a correct Python 3 solution for this coding contest problem. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1.
instruction
0
56,885
8
113,770
Tags: dsu, greedy, implementation, trees Correct Solution: ``` n = int(input()) minutesUsed = [0 for _ in range(n)] count = 1 for v in [int(k) for k in input().split(' ') if k]: if minutesUsed[v]: count += 1 else: minutesUsed[v] = 1 print(count) ```
output
1
56,885
8
113,771
Provide tags and a correct Python 3 solution for this coding contest problem. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1.
instruction
0
56,886
8
113,772
Tags: dsu, greedy, implementation, trees Correct Solution: ``` def getMinimum (arr, n): times = [None for i in range(0, n+1)] rooms = [None for i in range(0, n+1)] currentRoom = 0 times[0] = currentRoom rooms[currentRoom] = 0 t = 1 total = 1 currentRoom += 1 for i in range(0, n): # print('Times', times) # print('Rooms', rooms) if arr[i] >= t: t += 1 else: if times[arr[i]] != None: curRoom = times[arr[i]] lastTime = rooms[curRoom] if arr[i] != lastTime: total += 1 rooms[currentRoom] = t times[t] = currentRoom currentRoom += 1 else: rooms[curRoom] = t times[t] = curRoom else: rooms[currentRoom] = t times[t] = currentRoom currentRoom += 1 total += 1 t += 1 return total n = int(input()) arr = list(map(int, input().split())) print(getMinimum(arr, n)) ```
output
1
56,886
8
113,773
Provide tags and a correct Python 3 solution for this coding contest problem. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1.
instruction
0
56,887
8
113,774
Tags: dsu, greedy, implementation, trees Correct Solution: ``` n = int(input()) arr = list(map(int, input().split())) vis = [0] * (n+1) res = 1 for i in range(n): if vis[arr[i]] > 0: res += 1 vis[arr[i]] = 1 print(res) ```
output
1
56,887
8
113,775
Provide tags and a correct Python 3 solution for this coding contest problem. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1.
instruction
0
56,888
8
113,776
Tags: dsu, greedy, implementation, trees Correct Solution: ``` i = int(input()) ctc = [0] + list(map(int, input().split())) nm = 1 ptor = {0:1} for i in range(1, len(ctc)): if ctc[i] in ptor.keys(): ptor[i] = ptor[ctc[i]] del(ptor[ctc[i]]) else: nm+=1 ptor[i] = nm print(nm) ```
output
1
56,888
8
113,777
Provide tags and a correct Python 3 solution for this coding contest problem. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1.
instruction
0
56,889
8
113,778
Tags: dsu, greedy, implementation, trees Correct Solution: ``` def main(): n = int(input()) p = set() t = list(map(int, input().split())) p.add(1) for i in range(1, n): if t[i] == 0: p.add(i+1) continue if t[i] in p: p.remove(t[i]) p.add(i+1) else: p.add(i+1) print(len(p)) main() ```
output
1
56,889
8
113,779
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1. Submitted Solution: ``` def main(): n = int(input()) times = list(map(int, input().split())) mntm = set() mntm.add(0) ans = 1 for t in range(n): if times[t] in mntm: mntm.discard(times[t]) mntm.add(t + 1) else: ans += 1 mntm.add(t + 1) print(ans) main() ```
instruction
0
56,890
8
113,780
Yes
output
1
56,890
8
113,781
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1. Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) a1=[0]*1000000 k=0 for i in a: if a1[i]==0: k+=1 a1[i]=1 print(n-k+1) ```
instruction
0
56,891
8
113,782
Yes
output
1
56,891
8
113,783
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1. Submitted Solution: ``` input() rooms = set([0]) i = 0 for a in input().split(): a = int(a) try: rooms.remove(a) except Exception as e: pass i += 1 rooms.add(i) print(len(rooms)) ```
instruction
0
56,892
8
113,784
Yes
output
1
56,892
8
113,785
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1. Submitted Solution: ``` n = int(input()) notes = [int(x) for x in input().split()] greatest_cave = 1 visits = {0: 1} for time, curr in enumerate(notes, start=1): if curr in visits and visits[curr] != -1: visits[time] = visits[curr] visits[curr] = -1 else: greatest_cave += 1 visits[time] = greatest_cave print(greatest_cave) ```
instruction
0
56,893
8
113,786
Yes
output
1
56,893
8
113,787
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1. Submitted Solution: ``` n = int(input()) arr = list(map(int, input().split())) cnt_total = 0 cnt_tmp = 0 for i in range(n): for j in range(i, n): if arr[j] == arr[i]: cnt_tmp +=1 cnt_total= cnt_total +cnt_tmp-1 cnt_tmp = 0 print(cnt_total+1) ```
instruction
0
56,894
8
113,788
No
output
1
56,894
8
113,789
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1. Submitted Solution: ``` n=int(input()) a=input().split() c=1 v=set(a) for i in range(1,len(a)): if a[i-1]==a[i]: c+=1 if len(v)==1: print(c) else: print(len(v)) ```
instruction
0
56,895
8
113,790
No
output
1
56,895
8
113,791
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1. Submitted Solution: ``` n = int(input()) nums = [int(x) for x in input().split()] d = {0:0, 1:nums[0]} used = [False] * (2 * (10 ** 5) + 1) used[0] = True for i in range(1, n): if used[nums[i]]: d[i] = d[nums[i]] else: d[i] = nums[i] + 1 used[nums[i] + 1] = True print(sum(used)) ```
instruction
0
56,896
8
113,792
No
output
1
56,896
8
113,793
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: * If Petya has visited this room before, he writes down the minute he was in this room last time; * Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook. Output In the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs. Examples Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 Note In the first sample, sequence of rooms Petya visited could be, for example 1 β†’ 1 β†’ 2, 1 β†’ 2 β†’ 1 or 1 β†’ 2 β†’ 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 β†’ 2 β†’ 3 β†’ 1 β†’ 2 β†’ 1. Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] k = len(set(a)) r = len(a) if(r==1): print(1) elif( r==2): print(2) else: print(k) ```
instruction
0
56,897
8
113,794
No
output
1
56,897
8
113,795
Provide tags and a correct Python 3 solution for this coding contest problem. Alice is playing with some stones. Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones. Each time she can do one of two operations: 1. take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones); 2. take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has 0 stones. Can you help her? Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Next t lines describe test cases in the following format: Line contains three non-negative integers a, b and c, separated by spaces (0 ≀ a,b,c ≀ 100) β€” the number of stones in the first, the second and the third heap, respectively. In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied. Output Print t lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer β€” the maximum possible number of stones that Alice can take after making some operations. Example Input 3 3 4 5 1 0 5 5 3 2 Output 9 0 6 Note For the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is 9. It is impossible to make some operations to take more than 9 stones, so the answer is 9.
instruction
0
57,252
8
114,504
Tags: brute force, greedy, math Correct Solution: ``` import os, sys # zeilen = [l.strip() for l in sys.stdin.readlines()] t = int(sys.stdin.readline().strip()) for _ in range(t): a, b, c = map(int, sys.stdin.readline().strip().split()) anz2 = min(b, c//2) anz1 = min(a, (b-anz2) // 2) print(3*(anz1 + anz2)) ```
output
1
57,252
8
114,505
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≀ i ≀ n) book is wi. As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below. 1. He lifts all the books above book x. 2. He pushes book x out of the stack. 3. He puts down the lifted books without changing their order. 4. After reading book x, he puts book x on the top of the stack. <image> He decided to read books for m days. In the j-th (1 ≀ j ≀ m) day, he will read the book that is numbered with integer bj (1 ≀ bj ≀ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times. After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him? Input The first line contains two space-separated integers n (2 ≀ n ≀ 500) and m (1 ≀ m ≀ 1000) β€” the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1, w2, ..., wn (1 ≀ wi ≀ 100) β€” the weight of each book. The third line contains m space separated integers b1, b2, ..., bm (1 ≀ bj ≀ n) β€” the order of books that he would read. Note that he can read the same book more than once. Output Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books. Examples Input 3 5 1 2 3 1 3 2 3 1 Output 12 Note Here's a picture depicting the example. Each vertical column presents the stacked books. <image>
instruction
0
57,508
8
115,016
Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` n,m=map(int,input().split()) w=list(map(int,input().split())) l=list(map(int,input().split())) k=0 f=[] for x in l : x-=1 if x not in f : for y in f : k+=w[y] f=[x]+f else : for i in range(len(f)) : if f[i]!=x : k+=w[f[i]] else : break del(f[i]) f=[x]+f print(k) ```
output
1
57,508
8
115,017