message
stringlengths
2
433k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
113
108k
cluster
float64
12
12
__index_level_0__
int64
226
217k
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,630
12
113,260
Tags: data structures, greedy, implementation Correct Solution: ``` import sys input = sys.stdin.readline t=int(input()) for tests in range(t): n=int(input()) A=list(map(int,input().split())) compression_dict={a: ind for ind, a in enumerate(sorted(set(A)))} A=[compression_dict[a]+3 for a in A] # [2, 3, 0, 1, 4] LEN=n+6 BIT=[0]*(LEN+1) USE=[0]*(LEN+1) def update(v,w): while v<=LEN: BIT[v]+=w v+=(v&(-v)) def getvalue(v): ANS=0 while v!=0: ANS+=BIT[v] v-=(v&(-v)) return ANS def bisect_on_BIT(x): if x<=0: return 0 ANS=0 h=1<<(LEN.bit_length()-1) while h>0: if ANS+h<=LEN and BIT[ANS+h]<x: x-=BIT[ANS+h] ANS+=h h//=2 return ANS+1 USE[1]=1 USE[A[0]]=1 USE[n+5]=1 update(1,1) update(A[0],1) update(n+5,1) before=A[0] for a in A[1:]: #print(a) #print([getvalue(x) for x in range(n+6)]) if a==before: continue elif a>before: x=getvalue(before) u=bisect_on_BIT(x+1) if a<=u: if USE[a]==0: USE[a]=1 update(a,1) else: print("NO") break else: x=getvalue(before) u=bisect_on_BIT(x-1) #print(before,x,u) if a>=u: if USE[a]==0: USE[a]=1 update(a,1) else: print("NO") break before=a else: print("YES") ```
output
1
56,630
12
113,261
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,631
12
113,262
Tags: data structures, greedy, implementation Correct Solution: ``` INF=1e9+1 for ii in range(int(input())): n=int(input()) b=list(map(int,input().split())) m=b[0] l=[-INF] r=[INF] ans=1 for i in range(1,len(b)): if m>b[i]: if b[i]>l[-1]: r+=[m] elif b[i]<l[-1]: ans=0 break else : r+=[m] l.pop() elif m<b[i]: if b[i]<r[-1]: l+=[m] elif b[i]>r[-1]: ans=0 break else : l+=[m] r.pop() m=b[i] if(ans): print("YES") else : print("NO") ```
output
1
56,631
12
113,263
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,632
12
113,264
Tags: data structures, greedy, implementation Correct Solution: ``` import io import os from bisect import bisect_left, bisect_right from collections import Counter, defaultdict, deque from heapq import heappush, heappop, heapify from math import gcd, inf # https://raw.githubusercontent.com/cheran-senthil/PyRival/master/pyrival/data_structures/SortedList.py 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)) def solve(N, B): seen = set() sl = SortedList() seen.add(B[0]) sl.add(B[0]) BIG = 10 ** 9 + 10 for i, x in enumerate(B): if i == 0: continue # print(sl, "want med", x, "at", i) added = 0 if x not in seen: added += 1 sl.add(x) seen.add(x) for _ in range(2 - added): index = sl.bisect_left(x) if index - i < 0: sl.add(-BIG) else: sl.add(BIG) # print(" result", sl) if sl.bisect_left(x) != i: return "NO" assert len(sl) == 2 * i + 1 return "YES" if False: print(solve(4, [2, 1, 2, 3])) exit() print(solve(7, [1, 1, 3, 1, 0, -2, -1])) exit() if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline TC = int(input()) for tc in range(1, TC + 1): (N,) = [int(x) for x in input().split()] B = [int(x) for x in input().split()] ans = solve(N, B) print(ans) ```
output
1
56,632
12
113,265
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,633
12
113,266
Tags: data structures, greedy, implementation Correct Solution: ``` from sys import stdin, stdout import math import heapq R = lambda : stdin.readline().strip() RL = lambda f=None: list(map(f, R().split(' '))) if f else list(R().split(' ')) output = lambda x: stdout.write(str(x) + '\n') output_list = lambda x: output(' '.join(map(str, x))) for tc in range(int(R())): n = int(R()) a = RL(int) prev = a[0] left, right = [-int(1e10)], [int(1e10)] ans = True for i in a[1:]: if i < prev: if i < left[-1]: ans=False break right.append(prev) prev=i if i==left[-1]: left.pop() elif i>prev: if i > right[-1]: ans=False break left.append(prev) prev=i if i==right[-1]: right.pop() if ans: print('YES') continue print('NO') ```
output
1
56,633
12
113,267
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,634
12
113,268
Tags: data structures, greedy, implementation Correct Solution: ``` for s in[*open(0)][2::2]: a=*map(int,s.split()),;l=[-1e9];r=[1e9];o=0 for m,x in zip(a,a[1:]): if x>m: if x>r[-1]:o=1;break l+=m, if x==r[-1]:r.pop() elif x<m: if x<l[-1]:o=1;break r+=m, if x==l[-1]:l.pop() print("yNeOs"[o::2]) ```
output
1
56,634
12
113,269
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,635
12
113,270
Tags: data structures, greedy, implementation Correct Solution: ``` import bisect def updateQuery(BIT,index,val): while index < len(BIT): BIT[index] += val index += index&-index def sumQuery(BIT,index): total = 0 while index > 0: total += BIT[index] index -= index&-index return total def solve(arr,n,ans): nums = sorted(list(set(arr))) BIT = [0]*(len(nums)+1) present = set() left = 0 right = 0 for i in arr: index = bisect.bisect(nums,i-1) small = left + sumQuery(BIT,index) big = right + len(present) - sumQuery(BIT,index+1) #print(i,small,big,left,right) if abs(small-big) > 2: ans.append('NO') return if small < big: left += big-small elif big < small: right += small-big else: left += 1 right += 1 if i not in present: present.add(i) updateQuery(BIT,index+1,1) ans.append('YES') def main(): t = int(input()) ans = [] for i in range(t): n = int(input()) arr = list(map(int,input().split())) solve(arr,n,ans) print('\n'.join(ans)) main() ```
output
1
56,635
12
113,271
Provide tags and a correct Python 2 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,636
12
113,272
Tags: data structures, greedy, implementation Correct Solution: ``` from __future__ import print_function import sys import traceback from bisect import bisect_left, bisect_right, insort from itertools import chain, repeat, starmap from math import log from operator import add, eq, ne, gt, ge, lt, le, iadd from textwrap import dedent try: from collections.abc import Sequence, MutableSequence except ImportError: from collections import Sequence, MutableSequence from functools import wraps from sys import hexversion if hexversion < 0x03000000: from itertools import imap as map # pylint: disable=redefined-builtin from itertools import izip as zip # pylint: disable=redefined-builtin try: from thread import get_ident except ImportError: from dummy_thread import get_ident else: from functools import reduce try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): "Decorator to make a repr function return fillvalue for a recursive call." # pylint: disable=missing-docstring # Copied from reprlib in Python 3 # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py def decorating_function(user_function): repr_running = set() @wraps(user_function) def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper return decorating_function class SortedList(MutableSequence): DEFAULT_LOAD_FACTOR = 1000 def __init__(self, iterable=None, key=None): assert key is None self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=None): # pylint: disable=unused-argument if key is None: return object.__new__(cls) else: if cls is SortedList: return object.__new__(SortedKeyList) else: raise TypeError('inherit SortedKeyList for key argument') @property def key(self): # pylint: disable=useless-return return None def _reset(self, load): values = reduce(iadd, self._lists, []) self._clear() self._load = load self._update(values) def clear(self): self._len = 0 del self._lists[:] del self._maxes[:] del self._index[:] self._offset = 0 _clear = clear def add(self, value): _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, value) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _maxes[pos] = value else: insort(_lists[pos], value) self._expand(pos) else: _lists.append([value]) _maxes.append(value) self._len += 1 def _expand(self, pos): _load = self._load _lists = self._lists _index = self._index if len(_lists[pos]) > (_load << 1): _maxes = self._maxes _lists_pos = _lists[pos] half = _lists_pos[_load:] del _lists_pos[_load:] _maxes[pos] = _lists_pos[-1] _lists.insert(pos + 1, half) _maxes.insert(pos + 1, half[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort() self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _maxes.extend(sublist[-1] for sublist in _lists) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False pos = bisect_left(_maxes, value) if pos == len(_maxes): return False _lists = self._lists idx = bisect_left(_lists[pos], value) return _lists[pos][idx] == value def discard(self, value): _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, value) if pos == len(_maxes): return _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) pos = bisect_left(_maxes, value) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) else: raise ValueError('{0!r} not in list'.format(value)) def _delete(self, pos, idx): _lists = self._lists _maxes = self._maxes _index = self._index _lists_pos = _lists[pos] del _lists_pos[idx] self._len -= 1 len_lists_pos = len(_lists_pos) if len_lists_pos > (self._load >> 1): _maxes[pos] = _lists_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_lists) > 1: if not pos: pos += 1 prev = pos - 1 _lists[prev].extend(_lists[pos]) _maxes[prev] = _lists[prev][-1] del _lists[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_lists_pos: _maxes[pos] = _lists_pos[-1] else: del _lists[pos] del _maxes[pos] del _index[:] def _loc(self, pos, idx): if not pos: return idx _index = self._index if not _index: self._build_index() total = 0 # Increment pos to point in the index to len(self._lists[pos]). pos += self._offset # Iterate until reaching the root of the index tree at pos = 0. while pos: # Right-child nodes are at odd indices. At such indices # account the total below the left child node. if not pos & 1: total += _index[pos - 1] # Advance pos to the parent node. pos = (pos - 1) >> 1 return total + idx def _pos(self, idx): if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx) def _build_index(self): row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1 def __delitem__(self, index): if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return self._clear() elif self._len <= 8 * (stop - start): values = self._getitem(slice(None, start)) if stop < self._len: values += self._getitem(slice(stop, None)) self._clear() return self._update(values) indices = range(start, stop, step) # Delete items from greatest index to least so # that the indices remain valid throughout iteration. if step > 0: indices = reversed(indices) _pos, _delete = self._pos, self._delete for index in indices: pos, idx = _pos(index) _delete(pos, idx) else: pos, idx = self._pos(index) self._delete(pos, idx) def __getitem__(self, index): _lists = self._lists if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: # Whole slice optimization: start to stop slices the whole # sorted list. if start == 0 and stop == self._len: return reduce(iadd, self._lists, []) start_pos, start_idx = self._pos(start) start_list = _lists[start_pos] stop_idx = start_idx + stop - start # Small slice optimization: start index and stop index are # within the start list. if len(start_list) >= stop_idx: return start_list[start_idx:stop_idx] if stop == self._len: stop_pos = len(_lists) - 1 stop_idx = len(_lists[stop_pos]) else: stop_pos, stop_idx = self._pos(stop) prefix = _lists[start_pos][start_idx:] middle = _lists[(start_pos + 1):stop_pos] result = reduce(iadd, middle, prefix) result += _lists[stop_pos][:stop_idx] return result if step == -1 and start > stop: result = self._getitem(slice(stop + 1, start + 1)) result.reverse() return result # Return a list because a negative step could # reverse the order of the items and this could # be the desired behavior. indices = range(start, stop, step) return list(self._getitem(index) for index in indices) else: if self._len: if index == 0: return _lists[0][0] elif index == -1: return _lists[-1][-1] else: raise IndexError('list index out of range') if 0 <= index < len(_lists[0]): return _lists[0][index] len_last = len(_lists[-1]) if -len_last < index < 0: return _lists[-1][len_last + index] pos, idx = self._pos(index) return _lists[pos][idx] _getitem = __getitem__ def __setitem__(self, index, value): message = 'use ``del sl[index]`` and ``sl.add(value)`` instead' raise NotImplementedError(message) def __iter__(self): return chain.from_iterable(self._lists) def __reversed__(self): return chain.from_iterable(map(reversed, reversed(self._lists))) def reverse(self): raise NotImplementedError('use ``reversed(sl)`` instead') def islice(self, start=None, stop=None, reverse=False): _len = self._len if not _len: return iter(()) start, stop, _ = slice(start, stop).indices(self._len) if start >= stop: return iter(()) _pos = self._pos min_pos, min_idx = _pos(start) if stop == _len: max_pos = len(self._lists) - 1 max_idx = len(self._lists[-1]) else: max_pos, max_idx = _pos(stop) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): _lists = self._lists if min_pos > max_pos: return iter(()) if min_pos == max_pos: if reverse: indices = reversed(range(min_idx, max_idx)) return map(_lists[min_pos].__getitem__, indices) indices = range(min_idx, max_idx) return map(_lists[min_pos].__getitem__, indices) next_pos = min_pos + 1 if next_pos == max_pos: if reverse: min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices), ) if reverse: min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, reversed(sublist_indices)) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, sublist_indices) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices), ) def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _lists = self._lists # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if minimum is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_lists[min_pos], minimum) else: min_pos = bisect_right(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_lists[min_pos], minimum) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if maximum is None: max_pos = len(_maxes) - 1 max_idx = len(_lists[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_right(_lists[max_pos], maximum) else: max_pos = bisect_left(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_left(_lists[max_pos], maximum) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def __len__(self): """Return the size of the sorted list. ``sl.__len__()`` <==> ``len(sl)`` :return: size of sorted list """ return self._len def bisect_left(self, value): """Return an index to insert `value` in the sorted list. If the `value` is already present, the insertion point will be before (to the left of) any existing values. Similar to the `bisect` module in the standard library. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([10, 11, 12, 13, 14]) >>> sl.bisect_left(12) 2 :param value: insertion index of value in sorted list :return: index """ _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_left(self._lists[pos], value) return self._loc(pos, idx) def bisect_right(self, value): """Return an index to insert `value` in the sorted list. Similar to `bisect_left`, but if `value` is already present, the insertion point will be after (to the right of) any existing values. Similar to the `bisect` module in the standard library. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([10, 11, 12, 13, 14]) >>> sl.bisect_right(12) 3 :param value: insertion index of value in sorted list :return: index """ _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], value) return self._loc(pos, idx) bisect = bisect_right _bisect_right = bisect_right def count(self, value): """Return number of occurrences of `value` in the sorted list. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) >>> sl.count(3) 3 :param value: value to count in sorted list :return: count """ _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) pos_right = bisect_right(_maxes, value) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], value) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left def copy(self): """Return a shallow copy of the sorted list. Runtime complexity: `O(n)` :return: new sorted list """ return self.__class__(self) __copy__ = copy def append(self, value): """Raise not-implemented error. Implemented to override `MutableSequence.append` which provides an erroneous default implementation. :raises NotImplementedError: use ``sl.add(value)`` instead """ raise NotImplementedError('use ``sl.add(value)`` instead') def extend(self, values): """Raise not-implemented error. Implemented to override `MutableSequence.extend` which provides an erroneous default implementation. :raises NotImplementedError: use ``sl.update(values)`` instead """ raise NotImplementedError('use ``sl.update(values)`` instead') def insert(self, index, value): """Raise not-implemented error. :raises NotImplementedError: use ``sl.add(value)`` instead """ raise NotImplementedError('use ``sl.add(value)`` instead') def pop(self, index=-1): """Remove and return value at `index` in sorted list. Raise :exc:`IndexError` if the sorted list is empty or index is out of range. Negative indices are supported. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList('abcde') >>> sl.pop() 'e' >>> sl.pop(2) 'c' >>> sl SortedList(['a', 'b', 'd']) :param int index: index of value (default -1) :return: value :raises IndexError: if index is out of range """ if not self._len: raise IndexError('pop index out of range') _lists = self._lists if index == 0: val = _lists[0][0] self._delete(0, 0) return val if index == -1: pos = len(_lists) - 1 loc = len(_lists[pos]) - 1 val = _lists[pos][loc] self._delete(pos, loc) return val if 0 <= index < len(_lists[0]): val = _lists[0][index] self._delete(0, index) return val len_last = len(_lists[-1]) if -len_last < index < 0: pos = len(_lists) - 1 loc = len_last + index val = _lists[pos][loc] self._delete(pos, loc) return val pos, idx = self._pos(index) val = _lists[pos][idx] self._delete(pos, idx) return val def index(self, value, start=None, stop=None): """Return first index of value in sorted list. Raise ValueError if `value` is not present. Index must be between `start` and `stop` for the `value` to be considered present. The default value, None, for `start` and `stop` indicate the beginning and end of the sorted list. Negative indices are supported. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList('abcde') >>> sl.index('d') 3 >>> sl.index('z') Traceback (most recent call last): ... ValueError: 'z' is not in list :param value: value in sorted list :param int start: start index (default None, start of sorted list) :param int stop: stop index (default None, end of sorted list) :return: index of value :raises ValueError: if value is not present """ _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) if _lists[pos_left][idx_left] != value: raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 left = self._loc(pos_left, idx_left) if start <= left: if left <= stop: return left else: right = self._bisect_right(value) - 1 if start <= right: return start raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): """Return new sorted list containing all values in both sequences. ``sl.__add__(other)`` <==> ``sl + other`` Values in `other` do not need to be in sorted order. Runtime complexity: `O(n*log(n))` >>> sl1 = SortedList('bat') >>> sl2 = SortedList('cat') >>> sl1 + sl2 SortedList(['a', 'a', 'b', 'c', 't', 't']) :param other: other iterable :return: new sorted list """ values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values) __radd__ = __add__ def __iadd__(self, other): """Update sorted list with values from `other`. ``sl.__iadd__(other)`` <==> ``sl += other`` Values in `other` do not need to be in sorted order. Runtime complexity: `O(k*log(n))` -- approximate. >>> sl = SortedList('bat') >>> sl += 'cat' >>> sl SortedList(['a', 'a', 'b', 'c', 't', 't']) :param other: other iterable :return: existing sorted list """ self._update(other) return self def __mul__(self, num): """Return new sorted list with `num` shallow copies of values. ``sl.__mul__(num)`` <==> ``sl * num`` Runtime complexity: `O(n*log(n))` >>> sl = SortedList('abc') >>> sl * 3 SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']) :param int num: count of shallow copies :return: new sorted list """ values = reduce(iadd, self._lists, []) * num return self.__class__(values) __rmul__ = __mul__ def __imul__(self, num): """Update the sorted list with `num` shallow copies of values. ``sl.__imul__(num)`` <==> ``sl *= num`` Runtime complexity: `O(n*log(n))` >>> sl = SortedList('abc') >>> sl *= 3 >>> sl SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']) :param int num: count of shallow copies :return: existing sorted list """ values = reduce(iadd, self._lists, []) * num self._clear() self._update(values) return self def __make_cmp(seq_op, symbol, doc): "Make comparator method." def comparer(self, other): "Compare method for sorted list and sequence." if not isinstance(other, Sequence): return NotImplemented self_len = self._len len_other = len(other) if self_len != len_other: if seq_op is eq: return False if seq_op is ne: return True for alpha, beta in zip(self, other): if alpha != beta: return seq_op(alpha, beta) return seq_op(self_len, len_other) seq_op_name = seq_op.__name__ comparer.__name__ = '__{0}__'.format(seq_op_name) doc_str = """Return true if and only if sorted list is {0} `other`. ``sl.__{1}__(other)`` <==> ``sl {2} other`` Comparisons use lexicographical order as with sequences. Runtime complexity: `O(n)` :param other: `other` sequence :return: true if sorted list is {0} `other` """ comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol)) return comparer __eq__ = __make_cmp(eq, '==', 'equal to') __ne__ = __make_cmp(ne, '!=', 'not equal to') __lt__ = __make_cmp(lt, '<', 'less than') __gt__ = __make_cmp(gt, '>', 'greater than') __le__ = __make_cmp(le, '<=', 'less than or equal to') __ge__ = __make_cmp(ge, '>=', 'greater than or equal to') __make_cmp = staticmethod(__make_cmp) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values,)) @recursive_repr() def __repr__(self): """Return string representation of sorted list. ``sl.__repr__()`` <==> ``repr(sl)`` :return: string representation """ return '{0}({1!r})'.format(type(self).__name__, list(self)) def _check(self): """Check invariants of sorted list. Runtime complexity: `O(n)` """ try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) assert self._len == sum(len(sublist) for sublist in self._lists) # Check all sublists are sorted. for sublist in self._lists: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] # Check beginning/end of sublists are sorted. for pos in range(1, len(self._lists)): assert self._lists[pos - 1][-1] <= self._lists[pos][0] # Check _maxes index is the last value of each sublist. for pos in range(len(self._maxes)): assert self._maxes[pos] == self._lists[pos][-1] # Check sublist lengths are less than double load-factor. double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) # Check sublist lengths are greater than half load-factor for all # but the last sublist. half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) # Check index leaf nodes equal length of sublists. for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) # Check index branch nodes are the sum of their children. for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) print('len', self._len) print('load', self._load) print('offset', self._offset) print('len_index', len(self._index)) print('index', self._index) print('len_maxes', len(self._maxes)) print('maxes', self._maxes) print('len_lists', len(self._lists)) print('lists', self._lists) raise def identity(value): "Identity function." return value class SortedKeyList(SortedList): def __init__(self, iterable=None, key=identity): self._key = key self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._keys = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=identity): return object.__new__(cls) @property def key(self): return self._key def clear(self): self._len = 0 del self._lists[:] del self._keys[:] del self._maxes[:] del self._index[:] _clear = clear def add(self, value): _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(value) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _keys[pos].append(key) _maxes[pos] = key else: idx = bisect_right(_keys[pos], key) _lists[pos].insert(idx, value) _keys[pos].insert(idx, key) self._expand(pos) else: _lists.append([value]) _keys.append([key]) _maxes.append(key) self._len += 1 def _expand(self, pos): _lists = self._lists _keys = self._keys _index = self._index if len(_keys[pos]) > (self._load << 1): _maxes = self._maxes _load = self._load _lists_pos = _lists[pos] _keys_pos = _keys[pos] half = _lists_pos[_load:] half_keys = _keys_pos[_load:] del _lists_pos[_load:] del _keys_pos[_load:] _maxes[pos] = _keys_pos[-1] _lists.insert(pos + 1, half) _keys.insert(pos + 1, half_keys) _maxes.insert(pos + 1, half_keys[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _keys = self._keys _maxes = self._maxes values = sorted(iterable, key=self._key) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort(key=self._key) self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _keys.extend(list(map(self._key, _list)) for _list in _lists) _maxes.extend(sublist[-1] for sublist in _keys) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return False _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return False if _lists[pos][idx] == value: return True idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return False len_sublist = len(_keys[pos]) idx = 0 def discard(self, value): _maxes = self._maxes if not _maxes: return key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return len_sublist = len(_keys[pos]) idx = 0 def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} not in list'.format(value)) if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 def _delete(self, pos, idx): _lists = self._lists _keys = self._keys _maxes = self._maxes _index = self._index keys_pos = _keys[pos] lists_pos = _lists[pos] del keys_pos[idx] del lists_pos[idx] self._len -= 1 len_keys_pos = len(keys_pos) if len_keys_pos > (self._load >> 1): _maxes[pos] = keys_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_keys) > 1: if not pos: pos += 1 prev = pos - 1 _keys[prev].extend(_keys[pos]) _lists[prev].extend(_lists[pos]) _maxes[prev] = _keys[prev][-1] del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_keys_pos: _maxes[pos] = keys_pos[-1] else: del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): min_key = self._key(minimum) if minimum is not None else None max_key = self._key(maximum) if maximum is not None else None return self._irange_key( min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse, ) def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) _irange_key = irange_key def bisect_left(self, value): return self._bisect_key_left(self._key(value)) def bisect_right(self, value): return self._bisect_key_right(self._key(value)) bisect = bisect_right def bisect_key_left(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_left(self._keys[pos], key) return self._loc(pos, idx) _bisect_key_left = bisect_key_left def bisect_key_right(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_right(self._keys[pos], key) return self._loc(pos, idx) bisect_key = bisect_key_right _bisect_key_right = bisect_key_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return 0 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) total = 0 len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return total if _lists[pos][idx] == value: total += 1 idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return total len_sublist = len(_keys[pos]) idx = 0 def copy(self): return self.__class__(self, key=self._key) __copy__ = copy def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} is not in list'.format(value)) if _lists[pos][idx] == value: loc = self._loc(pos, idx) if start <= loc <= stop: return loc elif loc > stop: break idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} is not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values, key=self._key) __radd__ = __add__ def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values, key=self._key) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values, self.key)) @recursive_repr() def __repr__(self): type_name = type(self).__name__ return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key) def _check(self): try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) == len(self._keys) assert self._len == sum(len(sublist) for sublist in self._lists) # Check all sublists are sorted. for sublist in self._keys: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] # Check beginning/end of sublists are sorted. for pos in range(1, len(self._keys)): assert self._keys[pos - 1][-1] <= self._keys[pos][0] # Check _keys matches _key mapped to _lists. for val_sublist, key_sublist in zip(self._lists, self._keys): assert len(val_sublist) == len(key_sublist) for val, key in zip(val_sublist, key_sublist): assert self._key(val) == key # Check _maxes index is the last value of each sublist. for pos in range(len(self._maxes)): assert self._maxes[pos] == self._keys[pos][-1] # Check sublist lengths are less than double load-factor. double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) # Check sublist lengths are greater than half load-factor for all # but the last sublist. half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) # Check index leaf nodes equal length of sublists. for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) # Check index branch nodes are the sum of their children. for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) for _ in range(input()): n=input() a=[int(i) for i in raw_input().split()] s=SortedList() s.add(a[0]) for i in range(1,n): pos=s.bisect_left(a[i]) if pos>0 and s[pos-1]==a[i-1]: s.add(a[i]) continue if a[i]==a[i-1]: continue pos=s.bisect_left(a[i]+1) if pos!=len(s) and s[pos]==a[i-1]: s.add(a[i]) continue print("NO") break else: print("YES") ```
output
1
56,636
12
113,273
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. Submitted Solution: ``` from collections import deque from sys import stdin, gettrace if gettrace(): def inputi(): return input() else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def solve(): n = int(input()) bb = [int(a) for a in input().split()] pn = {} pn[bb[0]] = [None, None] c = bb[0] for b in bb[1:]: if b == c: continue if b < c: if pn[c][0] == None or b > pn[c][0]: if pn[c][0] != None: pn[pn[c][0]][1] = b pn[b] = [pn[c][0],c] pn[c][0] = b elif b < pn[c][0]: print('NO') return else: if pn[c][1] == None or b < pn[c][1]: if pn[c][1] != None: pn[pn[c][1]][0] = b pn[b] = [c, pn[c][1]] pn[c][1] = b elif b > pn[c][1]: print('NO') return c = b print('YES') def main(): t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main() ```
instruction
0
56,637
12
113,274
Yes
output
1
56,637
12
113,275
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. Submitted Solution: ``` import sys import math import heapq import bisect from collections import Counter from collections import defaultdict from io import BytesIO, IOBase import string import fractions 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 self.BUFSIZE = 8192 def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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, self.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") def get_int(): return int(input()) def get_ints(): return list(map(int, input().split(' '))) def get_int_grid(n): return [get_ints() for _ in range(n)] def get_str(): return input().strip() def get_strs(): return get_str().split(' ') def flat_list(arr): return [item for subarr in arr for item in subarr] def yes_no(b): if b: return "YES" else: return "NO" def binary_search(good, left, right, delta=1, right_true=False): """ Performs binary search ---------- Parameters ---------- :param good: Function used to perform the binary search :param left: Starting value of left limit :param right: Starting value of the right limit :param delta: Margin of error, defaults value of 1 for integer binary search :param right_true: Boolean, for whether the right limit is the true invariant :return: Returns the most extremal value interval [left, right] which is good function evaluates to True, alternatively returns False if no such value found """ limits = [left, right] while limits[1] - limits[0] > delta: if delta == 1: mid = sum(limits) // 2 else: mid = sum(limits) / 2 if good(mid): limits[int(right_true)] = mid else: limits[int(~right_true)] = mid if good(limits[int(right_true)]): return limits[int(right_true)] else: return False def prefix_sums(a): p = [0] for x in a: p.append(p[-1] + x) return p def solve_a(): n = get_int() a = get_ints() g = 0 for x in a: g = math.gcd(g, x) if min(a) < 0: return False else: return list(range(max(a) + 1)) def solve_b(): n = get_int() s = get_str() alpha = list(string.ascii_lowercase) for x in alpha: if x not in s: return x for i in range(26): for j in range(26): x, y = alpha[i], alpha[j] if x + y not in s: return x + y for i in range(26): for j in range(26): for k in range(26): x, y, z = alpha[i], alpha[j], alpha[k] if x + y + z not in s: return x + y + z return False def solve_c(): ratios = defaultdict(int) n = get_int() s = list(get_str()) d, k = 0, 0 ans = [] for x in s: if x == 'D': d += 1 else: k += 1 g = math.gcd(d, k) f = d // g, k // g ratios[f] += 1 ans.append(ratios[f]) return ans 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)) def solve_d(): n = get_int() b = get_ints() S = SortedList() S.add(float('inf')) S.add(-float('inf')) m = 0 for x in b: l = S.bisect_left(m) - 1 r = S.bisect_right(m) if S[l] <= x <= S[r]: m = x S.add(x) else: return False return True t = get_int() for _ in range(t): print(yes_no(solve_d())) ```
instruction
0
56,638
12
113,276
Yes
output
1
56,638
12
113,277
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. Submitted Solution: ``` import heapq from collections import Counter from math import gcd import io, os fastin = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def solve(): n = int(fastin()) b = list(map(int, fastin().split())) if n < 3: print("YES") return left, right = [], [] pivot = b[0] for j in range(1, n): if pivot == b[j]: continue if (right and b[j] > right[0]) or (left and b[j] < -left[0]): print("NO") return if b[j] > pivot: heapq.heappush(left, -pivot) pivot = b[j] if right and b[j] == right[0]: heapq.heappop(right) elif b[j] < pivot: heapq.heappush(right, pivot) pivot = b[j] if left and b[j] == -left[0]: heapq.heappop(left) print("YES") return testcase = int(fastin()) tn = 1 while tn <= testcase: solve() tn += 1 ```
instruction
0
56,639
12
113,278
Yes
output
1
56,639
12
113,279
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. Submitted Solution: ``` from __future__ import print_function import sys input = sys.stdin.readline import traceback from bisect import bisect_left, bisect_right, insort from itertools import chain, repeat, starmap from math import log from operator import add, eq, ne, gt, ge, lt, le, iadd from textwrap import dedent try: from collections.abc import Sequence, MutableSequence except ImportError: from collections import Sequence, MutableSequence from functools import wraps from sys import hexversion if hexversion < 0x03000000: from itertools import imap as map # pylint: disable=redefined-builtin from itertools import izip as zip # pylint: disable=redefined-builtin try: from thread import get_ident except ImportError: from dummy_thread import get_ident else: from functools import reduce try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): def decorating_function(user_function): repr_running = set() @wraps(user_function) def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper return decorating_function class SortedList(MutableSequence): DEFAULT_LOAD_FACTOR = 1000 def __init__(self, iterable=None, key=None): assert key is None self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=None): if key is None: return object.__new__(cls) else: if cls is SortedList: return object.__new__(SortedKeyList) else: raise TypeError('inherit SortedKeyList for key argument') @property def key(self): # pylint: disable=useless-return """Function used to extract comparison key from values. Sorted list compares values directly so the key function is none. """ return None def _reset(self, load): values = reduce(iadd, self._lists, []) self._clear() self._load = load self._update(values) def clear(self): self._len = 0 del self._lists[:] del self._maxes[:] del self._index[:] self._offset = 0 _clear = clear def add(self, value): _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, value) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _maxes[pos] = value else: insort(_lists[pos], value) self._expand(pos) else: _lists.append([value]) _maxes.append(value) self._len += 1 def _expand(self, pos): _load = self._load _lists = self._lists _index = self._index if len(_lists[pos]) > (_load << 1): _maxes = self._maxes _lists_pos = _lists[pos] half = _lists_pos[_load:] del _lists_pos[_load:] _maxes[pos] = _lists_pos[-1] _lists.insert(pos + 1, half) _maxes.insert(pos + 1, half[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: values.extend(chain.from_iterable(_lists)) values.sort() self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _maxes.extend(sublist[-1] for sublist in _lists) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False pos = bisect_left(_maxes, value) if pos == len(_maxes): return False _lists = self._lists idx = bisect_left(_lists[pos], value) return _lists[pos][idx] == value def discard(self, value): _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, value) if pos == len(_maxes): return _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) pos = bisect_left(_maxes, value) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) else: raise ValueError('{0!r} not in list'.format(value)) def _delete(self, pos, idx): _lists = self._lists _maxes = self._maxes _index = self._index _lists_pos = _lists[pos] del _lists_pos[idx] self._len -= 1 len_lists_pos = len(_lists_pos) if len_lists_pos > (self._load >> 1): _maxes[pos] = _lists_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_lists) > 1: if not pos: pos += 1 prev = pos - 1 _lists[prev].extend(_lists[pos]) _maxes[prev] = _lists[prev][-1] del _lists[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_lists_pos: _maxes[pos] = _lists_pos[-1] else: del _lists[pos] del _maxes[pos] del _index[:] def _loc(self, pos, idx): if not pos: return idx _index = self._index if not _index: self._build_index() total = 0 # Increment pos to point in the index to len(self._lists[pos]). pos += self._offset # Iterate until reaching the root of the index tree at pos = 0. while pos: # Right-child nodes are at odd indices. At such indices # account the total below the left child node. if not pos & 1: total += _index[pos - 1] # Advance pos to the parent node. pos = (pos - 1) >> 1 return total + idx def _pos(self, idx): if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx) def _build_index(self): row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1 def __delitem__(self, index): if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return self._clear() elif self._len <= 8 * (stop - start): values = self._getitem(slice(None, start)) if stop < self._len: values += self._getitem(slice(stop, None)) self._clear() return self._update(values) indices = range(start, stop, step) # Delete items from greatest index to least so # that the indices remain valid throughout iteration. if step > 0: indices = reversed(indices) _pos, _delete = self._pos, self._delete for index in indices: pos, idx = _pos(index) _delete(pos, idx) else: pos, idx = self._pos(index) self._delete(pos, idx) def __getitem__(self, index): _lists = self._lists if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: # Whole slice optimization: start to stop slices the whole # sorted list. if start == 0 and stop == self._len: return reduce(iadd, self._lists, []) start_pos, start_idx = self._pos(start) start_list = _lists[start_pos] stop_idx = start_idx + stop - start # Small slice optimization: start index and stop index are # within the start list. if len(start_list) >= stop_idx: return start_list[start_idx:stop_idx] if stop == self._len: stop_pos = len(_lists) - 1 stop_idx = len(_lists[stop_pos]) else: stop_pos, stop_idx = self._pos(stop) prefix = _lists[start_pos][start_idx:] middle = _lists[(start_pos + 1):stop_pos] result = reduce(iadd, middle, prefix) result += _lists[stop_pos][:stop_idx] return result if step == -1 and start > stop: result = self._getitem(slice(stop + 1, start + 1)) result.reverse() return result indices = range(start, stop, step) return list(self._getitem(index) for index in indices) else: if self._len: if index == 0: return _lists[0][0] elif index == -1: return _lists[-1][-1] else: raise IndexError('list index out of range') if 0 <= index < len(_lists[0]): return _lists[0][index] len_last = len(_lists[-1]) if -len_last < index < 0: return _lists[-1][len_last + index] pos, idx = self._pos(index) return _lists[pos][idx] _getitem = __getitem__ def __setitem__(self, index, value): message = 'use ``del sl[index]`` and ``sl.add(value)`` instead' raise NotImplementedError(message) def __iter__(self): return chain.from_iterable(self._lists) def __reversed__(self): return chain.from_iterable(map(reversed, reversed(self._lists))) def reverse(self): raise NotImplementedError('use ``reversed(sl)`` instead') def islice(self, start=None, stop=None, reverse=False): _len = self._len if not _len: return iter(()) start, stop, _ = slice(start, stop).indices(self._len) if start >= stop: return iter(()) _pos = self._pos min_pos, min_idx = _pos(start) if stop == _len: max_pos = len(self._lists) - 1 max_idx = len(self._lists[-1]) else: max_pos, max_idx = _pos(stop) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): _lists = self._lists if min_pos > max_pos: return iter(()) if min_pos == max_pos: if reverse: indices = reversed(range(min_idx, max_idx)) return map(_lists[min_pos].__getitem__, indices) indices = range(min_idx, max_idx) return map(_lists[min_pos].__getitem__, indices) next_pos = min_pos + 1 if next_pos == max_pos: if reverse: min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices), ) if reverse: min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, reversed(sublist_indices)) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, sublist_indices) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices), ) def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _lists = self._lists if minimum is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_lists[min_pos], minimum) else: min_pos = bisect_right(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_lists[min_pos], minimum) if maximum is None: max_pos = len(_maxes) - 1 max_idx = len(_lists[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_right(_lists[max_pos], maximum) else: max_pos = bisect_left(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_left(_lists[max_pos], maximum) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def __len__(self): return self._len def bisect_left(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_left(self._lists[pos], value) return self._loc(pos, idx) def bisect_right(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], value) return self._loc(pos, idx) bisect = bisect_right _bisect_right = bisect_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) pos_right = bisect_right(_maxes, value) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], value) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left def copy(self): return self.__class__(self) __copy__ = copy def append(self, value): raise NotImplementedError('use ``sl.add(value)`` instead') def extend(self, values): raise NotImplementedError('use ``sl.update(values)`` instead') def insert(self, index, value): raise NotImplementedError('use ``sl.add(value)`` instead') def pop(self, index=-1): if not self._len: raise IndexError('pop index out of range') _lists = self._lists if index == 0: val = _lists[0][0] self._delete(0, 0) return val if index == -1: pos = len(_lists) - 1 loc = len(_lists[pos]) - 1 val = _lists[pos][loc] self._delete(pos, loc) return val if 0 <= index < len(_lists[0]): val = _lists[0][index] self._delete(0, index) return val len_last = len(_lists[-1]) if -len_last < index < 0: pos = len(_lists) - 1 loc = len_last + index val = _lists[pos][loc] self._delete(pos, loc) return val pos, idx = self._pos(index) val = _lists[pos][idx] self._delete(pos, idx) return val def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) if _lists[pos_left][idx_left] != value: raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 left = self._loc(pos_left, idx_left) if start <= left: if left <= stop: return left else: right = self._bisect_right(value) - 1 if start <= right: return start raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values) __radd__ = __add__ def __iadd__(self, other): self._update(other) return self def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values) __rmul__ = __mul__ def __imul__(self, num): values = reduce(iadd, self._lists, []) * num self._clear() self._update(values) return self def __make_cmp(seq_op, symbol, doc): "Make comparator method." def comparer(self, other): "Compare method for sorted list and sequence." if not isinstance(other, Sequence): return NotImplemented self_len = self._len len_other = len(other) if self_len != len_other: if seq_op is eq: return False if seq_op is ne: return True for alpha, beta in zip(self, other): if alpha != beta: return seq_op(alpha, beta) return seq_op(self_len, len_other) seq_op_name = seq_op.__name__ comparer.__name__ = '__{0}__'.format(seq_op_name) doc_str = """Return true if and only if sorted list is {0} `other`. ``sl.__{1}__(other)`` <==> ``sl {2} other`` Comparisons use lexicographical order as with sequences. Runtime complexity: `O(n)` :param other: `other` sequence :return: true if sorted list is {0} `other` """ comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol)) return comparer __eq__ = __make_cmp(eq, '==', 'equal to') __ne__ = __make_cmp(ne, '!=', 'not equal to') __lt__ = __make_cmp(lt, '<', 'less than') __gt__ = __make_cmp(gt, '>', 'greater than') __le__ = __make_cmp(le, '<=', 'less than or equal to') __ge__ = __make_cmp(ge, '>=', 'greater than or equal to') __make_cmp = staticmethod(__make_cmp) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values,)) @recursive_repr() def __repr__(self): return '{0}({1!r})'.format(type(self).__name__, list(self)) def _check(self): """Check invariants of sorted list. Runtime complexity: `O(n)` """ try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) assert self._len == sum(len(sublist) for sublist in self._lists) # Check all sublists are sorted. for sublist in self._lists: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] # Check beginning/end of sublists are sorted. for pos in range(1, len(self._lists)): assert self._lists[pos - 1][-1] <= self._lists[pos][0] # Check _maxes index is the last value of each sublist. for pos in range(len(self._maxes)): assert self._maxes[pos] == self._lists[pos][-1] # Check sublist lengths are less than double load-factor. double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) # Check index leaf nodes equal length of sublists. for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) # Check index branch nodes are the sum of their children. for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) print('len', self._len) print('load', self._load) print('offset', self._offset) print('len_index', len(self._index)) print('index', self._index) print('len_maxes', len(self._maxes)) print('maxes', self._maxes) print('len_lists', len(self._lists)) print('lists', self._lists) raise def identity(value): "Identity function." return value for f in range(int(input())): n=int(input()) b=list(map(int,input().split())) s=SortedList() i=0 s.add(b[0]) poss=True for x in b: if s[i]==x: continue if i>0 and s[i-1]==x: i-=1 continue if i<len(s)-1 and s[i+1]==x: i+=1 continue if x<s[i]: if i==0 or x>s[i-1]: s.add(x) continue poss=False break if x>s[i]: if i==len(s)-1 or x<s[i+1]: s.add(x) i+=1 continue poss=False break print(["NO","YES"][poss]) ```
instruction
0
56,640
12
113,280
Yes
output
1
56,640
12
113,281
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. Submitted Solution: ``` import time #start_time = time.time() #def TIME_(): print(time.time()-start_time) import os, sys from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string, heapq as h 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") def getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def getBin(): return list(map(int,list(input()))) def isInt(s): return '0' <= s[0] <= '9' def ceil_(a,b): return (a+b-1)//b MOD = 10**9 + 7 """ """ #https://pastebin.com/sU55scy2 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)) """ X 2 X X X 1 2 X X 1 2 X X X 1 2 3 X X X """ def solve(): N = getInt() B = getInts() A = SortedList() A2 = SortedList() used = set() for i,b in enumerate(B): idx = A.bisect_left(b) idx2 = len(A) - A.bisect_right(b) #We have between idx and idx2 elements which are < b if b not in used: used.add(b) A.add(b) else: continue if idx*2 > i+1 or idx2*2 > i+1: return "NO" return "YES" for _ in range(getInt()): print(solve()) #solve() #TIME_() ```
instruction
0
56,641
12
113,282
No
output
1
56,641
12
113,283
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. Submitted Solution: ``` import random class Node: def __init__(self, val): self.val = val self.priority = random.random() self.left = None self.right = None self.num_children = 0 def get_num_left_children(self): if self.left: return self.left.num_children + 1 return 0 def get_num_right_children(self): return self.num_children - self.get_num_left_children() def __repr__(self): return str((self.val, self.priority)) class SimpleTreap: # with min heap. def __init__(self): self.root = None self.size = 0 def add_node(self, val): # assumes val doesn't appear in treap yet! self.size += 1 if not self.root: self.root = Node(val); return node = Node(val) current = self.root parents = [] while True: # add to BST. parents.append(current) current.num_children += 1 if node.val < current.val: if current.left: current = current.left else: current.left = node; break elif node.val > current.val: if current.right: current = current.right else: current.right = node; break current = node while parents: # reheap. parent = parents.pop() if parent.priority <= current.priority: return if parent.val > current.val: num_A = current.get_num_left_children() num_B = current.get_num_right_children() num_C = parent.get_num_right_children() parent.num_children = num_B + num_C current.num_children = parent.num_children + num_A + 1 parent.left = current.right current.right = parent if parents: parents[-1].left = current else: num_A = parent.get_num_left_children() num_B = current.get_num_left_children() num_C = current.get_num_right_children() parent.num_children = num_A + num_B current.num_children = parent.num_children + num_C + 1 parent.right = current.left current.left = parent if parents: if parents[-1].val > parent.val: parents[-1].left = current else: parents[-1].right = current else: self.root = current def get_pos(self, val): # assumes val appears in treap. current = self.root to_the_left = 0 while True: if current.val == val: return current.get_num_left_children() + to_the_left elif current.val > val: current = current.left else: to_the_left += current.get_num_left_children() + 1 current = current.right def solve(n, b): se = set(); prev = -1 treap = SimpleTreap() for i in range(n): if b[i] in se: x = treap.get_pos(b[i]) if abs(prev - x) >= 2: return False prev = x else: treap.add_node(b[i]) x = treap.get_pos(b[i]) se.add(b[i]) if not (prev == x or prev == x - 1): return False prev = x return True def main(): t = int(input()) for _ in range(t): n = int(input()) b = list(map(int, input().split())) if solve(n, b): print("YES") else: print("NO") main() ```
instruction
0
56,642
12
113,284
No
output
1
56,642
12
113,285
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. Submitted Solution: ``` def gcd(a,b): if b==0: return a return gcd(b,a%b) for _ in range(int(input())): n=int(input()) s=input() ans=[0]*n d=0 ans[0]=1 m={} if s[0]=='D': d=1 m[(1,0)]=1 else: m[(0,1)]=1 for i in range(1,n): if s[i]=='D': d+=1 g=gcd(d,i+1-d) a,b=d//g,(i+1-d)//g if (a,b) not in m: m[(a,b)]=1 else: m[(a,b)]+=1 ans[i]=m[(a,b)] print(*ans) ```
instruction
0
56,643
12
113,286
No
output
1
56,643
12
113,287
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≀ n ≀ 2 β‹… 10^5, -10^9 ≀ b_i ≀ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≀ b_i ≀ 10^9) β€” the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. Submitted Solution: ``` import time #start_time = time.time() #def TIME_(): print(time.time()-start_time) import os, sys from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string, heapq as h 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") def getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def getBin(): return list(map(int,list(input()))) def isInt(s): return '0' <= s[0] <= '9' def ceil_(a,b): return (a+b-1)//b MOD = 10**9 + 7 """ """ #https://pastebin.com/sU55scy2 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)) def solve(): N = getInt() B = getInts() used = set() num_used = 0 A = SortedList() for i,b in enumerate(B): if b in used: num_used += 1 continue idx = A.bisect_left(b) if 2*(idx-num_used) > i: return "NO" used.add(b) A.add(b) return "YES" for _ in range(getInt()): print(solve()) #solve() #TIME_() ```
instruction
0
56,644
12
113,288
No
output
1
56,644
12
113,289
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav has an array, consisting of (2Β·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. Input The first line contains an integer n (2 ≀ n ≀ 100). The second line contains (2Β·n - 1) integers β€” the array elements. The array elements do not exceed 1000 in their absolute value. Output In a single line print the answer to the problem β€” the maximum sum that Yaroslav can get. Examples Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 Note In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.
instruction
0
56,657
12
113,314
Tags: constructive algorithms Correct Solution: ``` #!/bin/python n = int(input()) a = list(map(int, input().split())) c = 0 for cc in a: if cc < 0: c += 1 if 0 in a: print(sum(abs(x) for x in a)) elif n % 2 == 0 and c % 2 == 1: print(sum(abs(x) for x in a) - 2*min(map(abs, a))) else: print(sum(abs(x) for x in a)) ```
output
1
56,657
12
113,315
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav has an array, consisting of (2Β·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. Input The first line contains an integer n (2 ≀ n ≀ 100). The second line contains (2Β·n - 1) integers β€” the array elements. The array elements do not exceed 1000 in their absolute value. Output In a single line print the answer to the problem β€” the maximum sum that Yaroslav can get. Examples Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 Note In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.
instruction
0
56,658
12
113,316
Tags: constructive algorithms Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) t = 0 for i in range(len(a)): if a[i] < 0: t += 1 a[i] = -a[i] if t % 2 == 0 or n % 2 == 1: print(sum(a)) else: print(sum(a) - min(a) * 2) ```
output
1
56,658
12
113,317
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav has an array, consisting of (2Β·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. Input The first line contains an integer n (2 ≀ n ≀ 100). The second line contains (2Β·n - 1) integers β€” the array elements. The array elements do not exceed 1000 in their absolute value. Output In a single line print the answer to the problem β€” the maximum sum that Yaroslav can get. Examples Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 Note In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.
instruction
0
56,659
12
113,318
Tags: constructive algorithms Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) c = 0 for cc in a: #print("Element is: " + str(cc)) # Reverse sign if cc < 0: c += 1 if 0 in a: #print("matched first condition") print(sum(abs(x) for x in a)) elif n % 2 == 0 and c % 2 == 1: #print("matched second condition") print(sum(abs(x) for x in a) - 2*min(map(abs, a))) else: #print("matched third condition") print(sum(abs(x) for x in a)) ```
output
1
56,659
12
113,319
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav has an array, consisting of (2Β·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. Input The first line contains an integer n (2 ≀ n ≀ 100). The second line contains (2Β·n - 1) integers β€” the array elements. The array elements do not exceed 1000 in their absolute value. Output In a single line print the answer to the problem β€” the maximum sum that Yaroslav can get. Examples Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 Note In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.
instruction
0
56,660
12
113,320
Tags: constructive algorithms Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) c = list(map(abs, a)) if len(list(filter(lambda x: x < 0, a))) & 1 and n + 1 & 1: print(sum(c) - 2 * min(c)) else: print(sum(c)) # Made By Mostafa_Khaled ```
output
1
56,660
12
113,321
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav has an array, consisting of (2Β·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. Input The first line contains an integer n (2 ≀ n ≀ 100). The second line contains (2Β·n - 1) integers β€” the array elements. The array elements do not exceed 1000 in their absolute value. Output In a single line print the answer to the problem β€” the maximum sum that Yaroslav can get. Examples Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 Note In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100. Submitted Solution: ``` n = int(input()) data = list(map(int, input().split())) x = 0 for element in data: if element < 0: x =+ abs(x) print(x) values = sorted(list(map(abs, data))) result = sum(values) if n % 2 == 0 and x % 2 == 1: result -= 2*values[0] print(result) ```
instruction
0
56,661
12
113,322
No
output
1
56,661
12
113,323
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≀ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation. Input The first line of input contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 109). The next line contains n integers p1, p2, ..., pn β€” the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem G1 (3 points), the constraints 1 ≀ n ≀ 6, 1 ≀ k ≀ 4 will hold. * In subproblem G2 (5 points), the constraints 1 ≀ n ≀ 30, 1 ≀ k ≀ 200 will hold. * In subproblem G3 (16 points), the constraints 1 ≀ n ≀ 100, 1 ≀ k ≀ 109 will hold. Output Output the answer with absolute or relative error no more than 1e - 9. Examples Input 3 1 1 2 3 Output 0.833333333333333 Input 3 4 1 3 2 Output 1.458333333333334 Note Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
instruction
0
56,708
12
113,416
Tags: dp Correct Solution: ``` f = lambda: map(int, input().split()) n, k = f() p = list(f()) r = range u = [l * l + l >> 1 for l in r(n + 1)] v = [(i, j) for i in r(n) for j in r(i + 1, n)] t = [[p[i] > p[j] for j in r(n)] for i in r(n)] a = [[0] * n for i in r(n)] b = [[0] * n for i in r(n)] c = [[0] * n for i in r(n)] for l in r(min(k, 1000)): for j in r(1, n): s, x = 0, a[j] for i in r(j): s += t[i][j] x[i + 1] = x[i] + s for i in r(n): s, y = 0, b[i] for j in r(n - 1, i, -1): s += t[i][j] y[j - 1] = y[j] + s for d in r(1, n): s, z = 0, c[d] for i in r(n - d): s += t[i][i + d] z[i + 1] = z[i] + s for i, j in v: d = j - i x, y, z = a[j], b[i], c[d] s = t[i][j] * (u[i] + u[d - 1] + u[n - j - 1]) s += x[j] - x[i] - x[d - 1] s += y[i] - y[j] - y[n - d] s += (i + 1) * (n - j) - z[n - d] + z[n - j - 1] + z[i] t[i][j] = s / u[n] print(sum(t[i][j] for i, j in v)) ```
output
1
56,708
12
113,417
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≀ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation. Input The first line of input contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 109). The next line contains n integers p1, p2, ..., pn β€” the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem G1 (3 points), the constraints 1 ≀ n ≀ 6, 1 ≀ k ≀ 4 will hold. * In subproblem G2 (5 points), the constraints 1 ≀ n ≀ 30, 1 ≀ k ≀ 200 will hold. * In subproblem G3 (16 points), the constraints 1 ≀ n ≀ 100, 1 ≀ k ≀ 109 will hold. Output Output the answer with absolute or relative error no more than 1e - 9. Examples Input 3 1 1 2 3 Output 0.833333333333333 Input 3 4 1 3 2 Output 1.458333333333334 Note Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. Submitted Solution: ``` f = lambda: map(int, input().split()) n, k = f() p = list(f()) a = [[0] * n for i in range(n)] g = [k * k - k >> 1 for k in range(n)] for i in range(n): for j in range(i + 1, n): if p[i] > p[j]: a[i][j] = 1 else: a[j][i] = 1 for t in range(max(k, 1000)): b = [[0] * n for i in range(n)] for i in range(n): for j in range(i + 1, n): p = q = 0 for x in range(j): d = min(i + 1, j - x, x + 1, j - i) p += d * a[x][j] q += d for y in range(i + 1, n): d = min(n - j, y - i, n - y, j - i) p += d * a[i][y] q += d for s in range(j, i + n): x, y = s - i, s - j d = min(i + 1, n - j, y + 1, n - x) p += d * a[x][y] q += d d = g[j - i] + g[i + 1] + g[n - j] b[i][j] = (p + d * a[i][j]) / (d + q) a = b for i in range(n): for j in range(i + 1, n): a[j][i] = 1 - a[i][j] s = 0 for i in range(n): for j in range(i + 1, n): s += a[i][j] print(s) ```
instruction
0
56,709
12
113,418
No
output
1
56,709
12
113,419
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≀ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation. Input The first line of input contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 109). The next line contains n integers p1, p2, ..., pn β€” the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem G1 (3 points), the constraints 1 ≀ n ≀ 6, 1 ≀ k ≀ 4 will hold. * In subproblem G2 (5 points), the constraints 1 ≀ n ≀ 30, 1 ≀ k ≀ 200 will hold. * In subproblem G3 (16 points), the constraints 1 ≀ n ≀ 100, 1 ≀ k ≀ 109 will hold. Output Output the answer with absolute or relative error no more than 1e - 9. Examples Input 3 1 1 2 3 Output 0.833333333333333 Input 3 4 1 3 2 Output 1.458333333333334 Note Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. Submitted Solution: ``` f = lambda: map(int, input().split()) n, k = f() p = list(f()) a = [[0] * n for i in range(n)] g = [i * i - i >> 1 for i in range(n)] for i in range(n): for j in range(i + 1, n): if p[i] > p[j]: a[i][j] = 1 else: a[j][i] = 1 for t in range(max(k, 1000)): b = [[0] * n for i in range(n)] for i in range(n): for j in range(i + 1, n): p = q = 0 for x in range(j): d = min(i + 1, j - x, x + 1, j - i) p += d * a[x][j] q += d for y in range(i + 1, n): d = min(n - j, y - i, n - y, j - i) p += d * a[i][y] q += d for s in range(j, i + n): x, y = s - i, s - j d = min(i + 1, n - j, y + 1, n - x) p += d * a[x][y] q += d d = g[j - i] + g[i + 1] + g[n - j] b[i][j] = (p + d * a[i][j]) / (d + q) a = b for i in range(n): for j in range(i + 1, n): a[j][i] = 1 - a[i][j] s = 0 for i in range(n): for j in range(i + 1, n): s += a[i][j] print(s) ```
instruction
0
56,710
12
113,420
No
output
1
56,710
12
113,421
Provide tags and a correct Python 3 solution for this coding contest problem. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3.
instruction
0
56,833
12
113,666
Tags: dp, greedy, implementation Correct Solution: ``` n=int(input()) l=list(map(int,input().split())) c=[[],[]] for i in l: c[i%2].append(i) c[0].sort() c[1].sort() ans=0 for i in c[0]: if i>0: ans+=i ans+=c[1][-1] for i in range(len(c[1])-2,0,-2): ans=max(ans,ans+c[1][i]+c[1][i-1]) print(ans) ```
output
1
56,833
12
113,667
Provide tags and a correct Python 3 solution for this coding contest problem. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3.
instruction
0
56,834
12
113,668
Tags: dp, greedy, implementation Correct Solution: ``` def main(): input() aa, l = list(map(int, input().split())), [] for i, a in enumerate(aa): if a & 1: l.append(i) elif a < 0: aa[i] = 0 l.sort(key=aa.__getitem__) i = 1 - len(l) & 1 if i: aa[l[0]] = 0 for j, k in zip(l[i::2], l[i + 1::2]): if aa[j] + aa[k] >= 0: break aa[j] = aa[k] = 0 print(sum(aa)) if __name__ == '__main__': main() ```
output
1
56,834
12
113,669
Provide tags and a correct Python 3 solution for this coding contest problem. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3.
instruction
0
56,835
12
113,670
Tags: dp, greedy, implementation Correct Solution: ``` input() a=[int(x) for x in input().split()] oc=0 ps=0 pmo=1e6 nmo=-1e6 for x in a: if x>0: ps+=x if x%2==1 and x>0 and pmo>x: pmo=x if x%2==1 and x>0: oc+=1 if x%2==1 and x<0 and nmo<x: nmo=x if oc%2==1: print(ps) else: print(max(ps-pmo,ps+nmo)) ```
output
1
56,835
12
113,671
Provide tags and a correct Python 3 solution for this coding contest problem. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3.
instruction
0
56,836
12
113,672
Tags: dp, greedy, implementation Correct Solution: ``` n = int(input()) arr = list(map(int,input().split())) s = sum([a for a in arr if a>0]) if s%2==1: print(s) else: mn_odd = 10001 for ele in arr: if ele%2==1 and ele>0: mn_odd = min(mn_odd,ele) mx_odd = -10001 for ele in arr: if ele%2==1 and ele<0: mx_odd = max(mx_odd,ele) print(max(s-mn_odd,s+mx_odd)) ```
output
1
56,836
12
113,673
Provide tags and a correct Python 3 solution for this coding contest problem. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3.
instruction
0
56,837
12
113,674
Tags: dp, greedy, implementation Correct Solution: ``` n = int(input()) arr = list(map(int,input().split())) pos,neg = [],[] for i in arr: if i>=0: pos+=[i] else: neg+=[i] ans = sum(pos) m_neg = -10**10 s_odd = 10**10 for i in neg: if i%2!=0: m_neg = max(m_neg,i) for i in pos: if i%2!=0: s_odd = min(s_odd,i) if ans%2!=0: print(ans) else: ans1,ans2 = ans,ans if m_neg!=(-10**10): ans1 = ans+m_neg if s_odd!=(10**10): ans2 = ans-s_odd # print(ans1,ans2,m_neg,s_odd) if ans1%2!=0 and ans2%2!=0: print(max(ans1,ans2)) elif ans1%2==0 and ans2%2!=0: print(ans2) elif ans1%2!=0 and ans2%2==0: print(ans1) ```
output
1
56,837
12
113,675
Provide tags and a correct Python 3 solution for this coding contest problem. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3.
instruction
0
56,838
12
113,676
Tags: dp, greedy, implementation Correct Solution: ``` n=int(input()) l=[int(i) for i in input().split()] s=sum(i for i in l if i>0) if s%2: print(s) else: m=[abs(i) for i in l if i%2==1] print(s-min(m)) ```
output
1
56,838
12
113,677
Provide tags and a correct Python 3 solution for this coding contest problem. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3.
instruction
0
56,839
12
113,678
Tags: dp, greedy, implementation Correct Solution: ``` n =int(input()) ar = list(map(int,input().split())) odd = [i for i in ar if i%2==1] even =[i for i in ar if i%2==0] odd.sort(reverse = True) even.sort(reverse = True) sum_even = 0 for i in even: if i>0: sum_even+=i preSum = [] preSum.append(odd[0]) for i in range(1,len(odd)): preSum.append(preSum[i-1]+odd[i]) max_odd_sum = preSum[0] for i in range(2,len(odd),2): max_odd_sum = max(max_odd_sum,preSum[i]) print(max(max_odd_sum+sum_even,max_odd_sum)) # print(odd) # print(even) # print(preSum) ```
output
1
56,839
12
113,679
Provide tags and a correct Python 3 solution for this coding contest problem. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3.
instruction
0
56,840
12
113,680
Tags: dp, greedy, implementation Correct Solution: ``` n=int(input()) a=list(map(int,input().split())) d=[] a.sort() e=[] for j in range(n): if(a[j]>=0): d.append(a[j]) else: e.append(a[j]) if(len(d)==0): for j in range(n-1,-1,-1): if(a[j]%2==1): val=a[j] break else: s=sum(d) if(s%2==1): val=s else: flag=0 s1=s s2=s for j in range(len(d)): if(d[j]%2==1): flag=1 s1-=d[j] break flag1=0 for j in range(len(e)-1,-1,-1): if(e[j]%2==1): flag1=1 s2+=e[j] break if(flag==0): val=s2 elif(flag1==0): val=s1 else: val=max(s1,s2) print(val) ```
output
1
56,840
12
113,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3. Submitted Solution: ``` input() items = list(map(int, input().split())) out=sum(filter(lambda n:n>0, items) ) if out%2==0: out=out-min(map(abs,filter(lambda n:n%2==1, items)) ) print(out) # Made By Mostafa_Khaled ```
instruction
0
56,841
12
113,682
Yes
output
1
56,841
12
113,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3. Submitted Solution: ``` def makeodd(listt): c=0 for r in range(len(listt)): if listt[r]%2==0: listt[r]="blah" c+=1 for e in range(c): listt.remove("blah") n=int(input()) inp=input() nums=inp.split(" ") for w in range(len(nums)): nums[w]=int(nums[w]) sum=0 tsum=0 neg=[] pos=[] an=False noTroll=True for i in range(n): if nums[i]>0: sum+=nums[i] pos.append(nums[i]) elif nums[i]<0: neg.append(nums[i]) if sum%2==1: print(sum) else: neg.sort() neg.reverse() pos.sort() makeodd(neg) makeodd(pos) z=0 while sum%2==0 and noTroll: if len(pos)>z and len(neg)>z: if pos[z]%2!=0 and pos[z]<neg[z]*-1: sum-=pos[z] break elif neg[z]%2!=0: for q in range(len(pos)-z): if pos[q+z]>neg[z]*-1 and pos[q+z]%2!=0: an=True break if an: sum+=neg[z] break elif len(neg)>z: if neg[z]%2!=0: sum+=neg[z] break else: if len(pos)>z: if pos[z]%2!=0: sum-=pos[z] break z+=1 print(sum) "yay" ```
instruction
0
56,842
12
113,684
Yes
output
1
56,842
12
113,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3. Submitted Solution: ``` n = int(input()) A = list(map(int, input().split())) dp = [[-9999999999, -9999999999]] for elem in A: dp += [[0, 0]] if elem % 2 == 0: dp[-1][0] = max(dp[-2][0] + elem, dp[-2][0], elem) dp[-1][1] = max(dp[-2][1] + elem, dp[-2][1]) else: dp[-1][0] = max(dp[-2][1] + elem, dp[-2][0]) dp[-1][1] = max(dp[-2][0] + elem, dp[-2][1], elem) print(dp[-1][1]) ```
instruction
0
56,843
12
113,686
Yes
output
1
56,843
12
113,687
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3. Submitted Solution: ``` n=int(input()) arr=list(map(int,input().split())) i=0 arr=sorted(arr,reverse=True) Sum=0 while i<n and arr[i]>0: Sum+=arr[i] i+=1 if Sum%2==1: print(Sum) else: k=i negSum=Sum while k<n and negSum%2==0: if arr[k]%2==1: negSum+=arr[k] k+=1 posSum=Sum j=i-1 while j>=0 and posSum%2==0: if arr[j]%2==1: posSum-=arr[j] j-=1 if posSum%2==0 and negSum%2==1: print(negSum) elif posSum%2==1 and negSum%2==0: print(posSum) else: print(max(posSum,negSum)) ```
instruction
0
56,844
12
113,688
Yes
output
1
56,844
12
113,689
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3. Submitted Solution: ``` def LOS(L): x=min(L) L2=[0]*(len(L)) for i in range(len(L)): if(L[i]%2!=0): L2[i]=L[i] else: L2[i]=x for i in range(1,len(L)): for j in range(i): if((L[i]+L[j])%2!=0 and L[i]+L[j]>L2[i]): L2[i]=L[i]+L[j] return max(L2) i=int(input("")) L=[x for x in input("").split()] for i in range(len(L)): L[i]=int(L[i]) print(LOS(L)) ```
instruction
0
56,845
12
113,690
No
output
1
56,845
12
113,691
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3. Submitted Solution: ``` n = int(input()) l = list(map(int,input().split())) odd_pos = [] odd_neg = [] even_pos = [] even_neg = [] for i in range(len(l)): if l[i]%2 == 1 and l[i] > 0: odd_pos.append(l[i]) elif l[i]%2 == 0 and l[i] > 0: even_pos.append(l[i]) elif l[i]%2 == 1 and l[i] < 0: odd_neg.append(l[i]) else: even_neg.append(l[i]) if len(odd_pos): odd_pos.sort(reverse=True) if len(odd_pos)%2 == 0: odd_pos = odd_pos[:len(odd_pos)-1] ans1 = sum(odd_pos) else: ans1 = sum(odd_pos) if len(even_pos): ans2 = sum(even_pos) else: ans2 = 0 print(ans1 + ans2) elif len(odd_neg): ans1 = max(odd_neg) if len(even_pos): ans2 = sum(even_pos) else: ans2 = 0 print(ans1+ans2) ```
instruction
0
56,846
12
113,692
No
output
1
56,846
12
113,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3. Submitted Solution: ``` n = int(input()) l = list(map(int, input().split())) odd = [] even = [] for i in range(n): if l[i] % 2 == 0: if l[i] > 0: even.append(l[i]) else: odd.append(l[i]) odd.sort(reverse=True) even.sort(reverse=True) ans = 0 for i in range(len(odd)): if odd[i] < 0: if ans == 0: ans += odd[i] break else: break else: ans += odd[i] print(ans + sum(even)) ```
instruction
0
56,847
12
113,694
No
output
1
56,847
12
113,695
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. Input The first line contains integer number n (1 ≀ n ≀ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≀ ai ≀ 104). The sequence contains at least one subsequence with odd sum. Output Print sum of resulting subseqeuence. Examples Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 Note In the first example sum of the second and the fourth elements is 3. Submitted Solution: ``` n=int(input()) ligne = input().split(" ") if(n==1): print(ligne[0]) else: l=[] for i in range(n): l.append(int(ligne[i])) maxi=max(l) l.remove(max(l)) j=max(l) nmaxi=maxi+j while(maxi%2==0 or len(l)>0): if(nmaxi>maxi): if(nmaxi%2!=0): maxi=nmaxi l.remove(j) j=max(l) nmaxi=maxi+j else: l.remove(j) j=max(l) nmaxi=maxi+j elif(nmaxi%2!=0): #maxi=nmaxi break print(maxi) ```
instruction
0
56,848
12
113,696
No
output
1
56,848
12
113,697
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9
instruction
0
56,849
12
113,698
Tags: data structures, divide and conquer, dsu, sortings Correct Solution: ``` import sys def pro(): return sys.stdin.readline().strip() def rop(): return map(int, pro().split()) def a_b_b(a, b): return a > b def a_br_b(a, b): return a >= b def a_m_b(a, b): return a < b def a_mr_b(a, b): return a <= b def ry(a, c, t): q = len(a) x = [(t, -1)] r = [0] * q for i in range(len(a)): v = a[i] while c(v, x[-1][0]): x.pop() r[i] = x[-1][1] x.append((v, i)) return r def tyr(a): q = len(a) r = [0] * q for i in range(q): r[q - i - 1] = q - a[i] - 1 return r def main(): s = int(pro()) a = list(rop()) z = a[::-1] o = 10 ** 9 r = 0 m = ry(a, a_b_b, o) n = tyr(ry(z, a_br_b, o)) b = ry(a, a_m_b, -o) v = tyr(ry(z, a_mr_b, -o)) for i in range(s): r += a[i] * ((i - m[i]) * (n[i] - i) - (i - b[i]) * (v[i] - i)) print(r) main() ```
output
1
56,849
12
113,699
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9
instruction
0
56,850
12
113,700
Tags: data structures, divide and conquer, dsu, sortings Correct Solution: ``` ##################################### import atexit, io, sys, collections, math, heapq, fractions,copy, os from io import BytesIO, IOBase ##################################### python 3 START 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") ##################################### python 3 END n = int(input()) ais = list(map(int, input().split())) def build(nums,iter, flag,mark): h = {} stack = collections.deque([]) for i in iter: if flag: if mark: while(stack and nums[stack[-1]] >= nums[i]): h[stack.pop()] = i else: while(stack and nums[stack[-1]] > nums[i]): h[stack.pop()] = i else: if mark: while(stack and nums[stack[-1]] < nums[i]): h[stack.pop()] = i else: while(stack and nums[stack[-1]] <= nums[i]): h[stack.pop()] = i stack.append(i) return h def f(ais,n): ans = 0 for b in [False, True]: left = build(ais, range(len(ais))[::-1], b, False) right = build(ais, range(len(ais)), b, True) ''' print ('MAX' if b is False else 'MIN',ais) for i in range(len(ais)): l = (i - (left[i] if i in left else -1) ) r = ((right[i] if i in right else n) - i) q= l*r print ('index = ', i, '|',left[i] if i in left else -1, right[i] if i in right else n, 'quantity = ', q) ''' for i in range(len(ais)): l = (i - (left[i] if i in left else -1) ) r = ((right[i] if i in right else n) - i) q = l * r * ais[i] if b: q*=-1 ans += q return ans print (f(ais,n)) ```
output
1
56,850
12
113,701
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9
instruction
0
56,851
12
113,702
Tags: data structures, divide and conquer, dsu, sortings Correct Solution: ``` ##################################### import atexit, io, sys, collections, math, heapq, fractions,copy, os from io import BytesIO, IOBase ##################################### python 3 START 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") ##################################### python 3 END n = int(input()) ais = list(map(int, input().split())) def check(a,b,flag, mark): return (a >= b if mark else a > b) if flag else (a <= b if mark else a < b) def build(nums,iter, flag,mark,dv): h,stack = [dv for i in range(len(nums))],collections.deque([]) for i in iter: while(stack and check(nums[stack[-1]], nums[i], flag, mark)): h[stack.pop()] = i stack.append(i) return h def f(ais,n): ans = 0 left = [None,None] right = [None,None] for b in [False,True]: left[int(b)],right[int(b)] = build(ais, range(len(ais)-1,-1,-1), b, False, -1),build(ais, range(len(ais)), b, True, n) for i in range(len(ais)): ans += ((i - left[0][i]) * (right[0][i] - i) * ais[i]) - (i - left[1][i]) * (right[1][i] - i) * ais[i] return ans print (f(ais,n)) ```
output
1
56,851
12
113,703
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9
instruction
0
56,852
12
113,704
Tags: data structures, divide and conquer, dsu, sortings Correct Solution: ``` ##################################### import atexit, io, sys, collections, math, heapq, fractions,copy, os from io import BytesIO, IOBase ##################################### python 3 START 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") ##################################### python 3 END n = int(input()) ais = list(map(int, input().split())) def check(a,b,flag, mark): if flag: return a >= b if mark else a > b else: return a <= b if mark else a < b def build(nums,iter, flag,mark,dv): h,stack = [dv for i in range(len(nums))],collections.deque([]) for i in iter: while(stack and check(nums[stack[-1]], nums[i], flag, mark)): h[stack.pop()] = i stack.append(i) return h def f(ais,n): ans = 0 for b in [False, True]: left,right = build(ais, range(len(ais))[::-1], b, False, -1),build(ais, range(len(ais)), b, True, n) for i in range(len(ais)): l = i - left[i]# if i in left else -1) ) r = right[i] - i #if i in right else n) - i) q = l * r * ais[i] ans += q if not(b) else -q return ans print (f(ais,n)) ```
output
1
56,852
12
113,705
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9
instruction
0
56,853
12
113,706
Tags: data structures, divide and conquer, dsu, sortings Correct Solution: ``` ##################################### import atexit, io, sys, collections, math, heapq, fractions,copy, os from io import BytesIO, IOBase ##################################### python 3 START 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") ##################################### python 3 END n = int(input()) ais = list(map(int, input().split())) def check(a,b,flag, mark): if flag: return a >= b if mark else a > b else: return a <= b if mark else a < b def build(nums,iter, flag,mark,dv): h,stack = [dv for i in range(len(nums))],collections.deque([]) for i in iter: while(stack and check(nums[stack[-1]], nums[i], flag, mark)): h[stack.pop()] = i stack.append(i) return h def f(ais,n): ans = 0 for b in [False, True]: left,right = build(ais, range(len(ais)-1,-1,-1), b, False, -1),build(ais, range(len(ais)), b, True, n) for i in range(len(ais)): q = (i - left[i]) * (right[i] - i) * ais[i] ans += q if not(b) else -q return ans print (f(ais,n)) ```
output
1
56,853
12
113,707
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9
instruction
0
56,854
12
113,708
Tags: data structures, divide and conquer, dsu, sortings Correct Solution: ``` n = int(input()) a = list(map(int,input().split())) left = [None for _ in range(n)] right = [None for _ in range(n)] left1 = [None for _ in range(n)] right1 = [None for _ in range(n)] class Stack(object): def __init__(self): self.c = [] def push(self,new): self.c.append(new) def pop(self): return self.c.pop(-1) def vide(self): return self.c == [] def peek(self): return self.c[-1] def calculleft(): s = Stack() for i in range(n): while not s.vide() and a[s.peek()] > a[i]: s.pop() if not s.vide(): left[i] = s.peek() else: left[i] = -1 s.push(i) def calculright(): s = Stack() for i in range(n-1,-1,-1): while not s.vide() and a[s.peek()] >= a[i]: s.pop() if not s.vide(): right[i] = s.peek() else: right[i] = n s.push(i) def calculleft1(): s = Stack() for i in range(n): while not s.vide() and a[s.peek()] < a[i]: s.pop() if not s.vide(): left1[i] = s.peek() else: left1[i] = -1 s.push(i) def calculright1(): s = Stack() for i in range(n-1,-1,-1): while not s.vide() and a[s.peek()] <= a[i]: s.pop() if not s.vide(): right1[i] = s.peek() else: right1[i] = n s.push(i) res = 0 calculleft() calculright() calculleft1() calculright1() res2 = 0 for i in range(n): res += (i-left[i])*(right[i]-i)*a[i] res2 += (i-left1[i])*(right1[i]-i)*a[i] print(res2-res) ```
output
1
56,854
12
113,709
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9
instruction
0
56,855
12
113,710
Tags: data structures, divide and conquer, dsu, sortings Correct Solution: ``` def solve1(a, n): left=[] st=[] i=0 while i<(n): if not st: left.append(-1) st.append(i) elif st and a[i]<a[st[-1]]: left.append(st[-1]) st.append(i) else: while st and a[i]>a[st[-1]]: st.pop() if not st: st.append(i) left.append(-1) else: left.append(st[-1]) st.append(i) i+=1 # print(left) right=[] st=[] i=n-1 while i>(-1): if not st: right.append(n) st.append(i) elif st and a[i]<a[st[-1]]: right.append(st[-1]) st.append(i) else: while st and a[i]>=a[st[-1]]: st.pop() if not st: st.append(i) right.append(n) else: right.append(st[-1]) st.append(i) i-=1 right=right[::-1] c=0 for i in range(len(left)): x=(right[i]-i)*(i-left[i])*a[i] # print(x) if x==0: c+=a[i] else: c+=x # print(c) # print(a) # print(left) # print(right) return c def solve2(a, n): left=[] st=[] i=0 while i<(n): if not st: left.append(-1) st.append(i) elif st and a[i]>a[st[-1]]: left.append(st[-1]) st.append(i) else: while st and a[i]<a[st[-1]]: st.pop() if not st: st.append(i) left.append(-1) else: left.append(st[-1]) st.append(i) i+=1 # print(left) right=[] st=[] i=n-1 while i>(-1): if not st: right.append(n) st.append(i) elif st and a[i]>a[st[-1]]: right.append(st[-1]) st.append(i) else: while st and a[i]<=a[st[-1]]: st.pop() if not st: st.append(i) right.append(n) else: right.append(st[-1]) st.append(i) i-=1 right=right[::-1] # print(right) c=0 for i in range(len(left)): x=(right[i]-i)*(i-left[i])*a[i] # print(x) if x==0: c+=a[i] else: c+=x # print(c) # print(a) # print(left) # print(right) return c n=int(input()) arr=[int(x) for x in input().split()] # solve2(arr,n) # print((solve1(arr,n))) # print((solve2(arr,n))) # print() # (solve2(arr,n)) print(solve1(arr,n)-solve2(arr,n)) ```
output
1
56,855
12
113,711
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9
instruction
0
56,856
12
113,712
Tags: data structures, divide and conquer, dsu, sortings Correct Solution: ``` #Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue, bisect #sys.stdin = open("input.txt", "r") MOD = 10**9+7 sys.setrecursionlimit(1000000) def mxr(x): n = len(x) ans = [n for i in range(n)] s = [] for i in range(n): while len(s) > 0 and x[s[-1]] < x[i]: ans[s.pop()] = i s.append(i) return ans def mnr(x): n = len(x) ans = [n for i in range(n)] s = [] for i in range(n): while len(s) > 0 and x[s[-1]] > x[i]: ans[s.pop()] = i s.append(i) return ans def mxl(x): ans = [-1 for i in range(n)] s = [] for i in range(n-1, -1, -1): while len(s) > 0 and x[s[-1]] <= x[i]: ans[s.pop()] = i s.append(i) return ans def mnl(x): ans = [-1 for i in range(n)] s = [] for i in range(n-1, -1, -1): while len(s) > 0 and x[s[-1]] >= x[i]: ans[s.pop()] = i s.append(i) return ans n = int(input()) a = list(map(int, input().split())) maxl = mxl(a) minl = mnl(a) maxr = mxr(a) minr = mnr(a) ans = 0 for i in range(n): mxrng = (maxr[i]-i)*(i-maxl[i]) mnrng = (minr[i]-i)*(i-minl[i]) ans += a[i]*(mxrng-mnrng) print(ans) ```
output
1
56,856
12
113,713
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9 Submitted Solution: ``` 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") #'%.9f'%ans #sys.stdout.flush() ########################################################## def add(i,val): while i<=n: bit[i].append(val) i+=(i&-i) def query(i,x): s=0 while i>0: pos=bisect.bisect_left(bit[i],x) s+=len(bit[i])-pos i-=(i&-i) return s from collections import Counter import math bit=[] import bisect from string import ascii_lowercase as al #for _ in range(int(input())): #n=int(input()) #n, k = map(int, input().split()) #arr=list(map(int,input().split())) #for i in range(n): def find_max(): left=[] st=[] for i in range(n): if not st: left.append(-1) st.append(i) elif st and arr[i]<arr[st[-1]]: left.append(st[-1]) st.append(i) else: while st and arr[st[-1]]<=arr[i]: st.pop() if not st: st.append(i) left.append(-1) else: left.append(st[-1]) st.append(i) right=[] st=[] for i in range(n-1,-1,-1): if not st: st.append(i) right.append(n) elif arr[i]<arr[st[-1]]: right.append(st[-1]) st.append(i) else: while st and arr[st[-1]]<arr[i]: st.pop() if st: right.append(st[-1]) st.append(i) else: right.append(n) st.append(i) ans=0 right=right[::-1] for i in range(n): x=(right[i]-i)*(i-left[i])*arr[i] if x==0: ans+=arr[i] else: ans+=x return ans def find_min(): left = [] st = [] for i in range(n): if not st: left.append(-1) st.append(i) elif st and arr[i] > arr[st[-1]]: left.append(st[-1]) st.append(i) else: while st and arr[st[-1]] >=arr[i]: st.pop() if not st: st.append(i) left.append(-1) else: left.append(st[-1]) st.append(i) right = [] st = [] for i in range(n - 1, -1, -1): if not st: st.append(i) right.append(n) elif arr[i] > arr[st[-1]]: right.append(st[-1]) st.append(i) else: while st and arr[st[-1]] >arr[i]: st.pop() if st: right.append(st[-1]) st.append(i) else: right.append(n) st.append(i) ans = 0 right = right[::-1] for i in range(n): x = (right[i] - i) * (i - left[i])*arr[i] if x == 0: ans += arr[i] else: ans += x #print("%%%%%%%%%%%%") return ans n=int(input()) arr=list(map(int,input().split())) print(find_max()-find_min()) ```
instruction
0
56,857
12
113,714
Yes
output
1
56,857
12
113,715
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9 Submitted Solution: ``` ##################################### import atexit, io, sys, collections, math, heapq, fractions,copy, os from io import BytesIO, IOBase ##################################### python 3 START 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") ##################################### python 3 END n = int(input()) ais = list(map(int, input().split())) def check(a,b,flag, mark): return (a >= b if mark else a > b) if flag else (a <= b if mark else a < b) def build(nums,iter, flag,mark,dv): h,stack = [dv for i in range(len(nums))],collections.deque([]) for i in iter: while(stack and check(nums[stack[-1]], nums[i], flag, mark)): h[stack.pop()] = i stack.append(i) return h def f(ais,n): ans = 0 left = [None,None] right = [None,None] for b in [False,True]: left[int(b)],right[int(b)] = build(ais, range(len(ais)-1,-1,-1), b, False, -1),build(ais, range(len(ais)), b, True, n) for i in range(len(ais)): q = (i - left[0][i]) * (right[0][i] - i) * ais[i] ans += q q = (i - left[1][i]) * (right[1][i] - i) * ais[i] ans -= q return ans print (f(ais,n)) ```
instruction
0
56,858
12
113,716
Yes
output
1
56,858
12
113,717
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array. For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: * [1] (from index 1 to index 1), imbalance value is 0; * [1, 4] (from index 1 to index 2), imbalance value is 3; * [1, 4, 1] (from index 1 to index 3), imbalance value is 3; * [4] (from index 2 to index 2), imbalance value is 0; * [4, 1] (from index 2 to index 3), imbalance value is 3; * [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a. Input The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one integer β€” the imbalance value of a. Example Input 3 1 4 1 Output 9 Submitted Solution: ``` #taken from https://stackoverflow.com/questions/30698441/optimal-way-to-find-sums-of-all-contiguous-sub-arrays-max-difference def max_sums(d): stack = [(-1, float('inf'))] sum_ = 0 for i, x in enumerate(d): while x > stack[-1][1]: prev_i, prev_x = stack.pop() prev_prev_i, prev_prev_x = stack[-1] sum_ += prev_x * (i - prev_i) * (prev_i - prev_prev_i) stack.append((i, x)) while len(stack) > 1: prev_i, prev_x = stack.pop() prev_prev_i, prev_prev_x = stack[-1] sum_ += prev_x * (len(d) - prev_i) * (prev_i - prev_prev_i) return sum_ def max_differences_sum(d): return max_sums(d) + max_sums([-x for x in d]) n=int(input()) l=list(map(int,input().split())) print(max_differences_sum(l)) ```
instruction
0
56,859
12
113,718
Yes
output
1
56,859
12
113,719