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. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10].
instruction
0
18,633
12
37,266
Tags: data structures, greedy Correct Solution: ``` import sys as _sys def main(): n, = _read_ints() a = tuple(_read_ints()) m, = _read_ints() queries = (tuple(_read_ints()) for i_query in range(m)) result = process_queries(a, queries) print(*result, sep='\n') def _read_line(): result = _sys.stdin.readline() assert result[-1] == "\n" return result[:-1] def _read_ints(): return map(int, _read_line().split()) def process_queries(sequence, queries): sequence = tuple(sequence) indices_to_select = sorted( range(len(sequence)), key=lambda index: (-sequence[index], index) ) enumerated_queries = sorted(enumerate(queries), key=lambda iv: iv[1][0])[::-1] queries_responses = [None] * len(enumerated_queries) selections_tree = [0] * (len(sequence) + 1) selected_n = 0 for index_to_select in indices_to_select: _fenwick_tree_add(selections_tree, index_to_select, 1) selected_n += 1 while enumerated_queries and enumerated_queries[-1][1][0] == selected_n: query_index, (_k, subseq_index) = enumerated_queries.pop() seq_index = _find_seq_index_by_subseq_index(selections_tree, subseq_index) queries_responses[query_index] = sequence[seq_index] return queries_responses def _find_seq_index_by_subseq_index(tree, subseq_i): seq_length = len(tree) - 1 min_i = 0 max_i = seq_length - 1 while min_i != max_i: mid_i = (min_i + max_i) // 2 if _fenwick_tree_prefix_sum(tree, mid_i) < subseq_i: min_i = mid_i + 1 else: max_i = mid_i return min_i def _fenwick_tree_prefix_sum(tree, i): i += 1 result = 0 while i != 0: result += tree[i] i -= i & (-i) return result def _fenwick_tree_add(tree, i, x): i += 1 while i < len(tree): tree[i] += x i += i & (-i) if __name__ == '__main__': main() ```
output
1
18,633
12
37,267
Provide tags and a correct Python 3 solution for this coding contest problem. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10].
instruction
0
18,634
12
37,268
Tags: data structures, greedy Correct Solution: ``` from collections import defaultdict import sys as _sys def main(): n, = _read_ints() a = tuple(_read_ints()) m, = _read_ints() queries = (tuple(_read_ints()) for i_query in range(m)) result = process_queries(a, queries) print(*result, sep='\n') def _read_line(): result = _sys.stdin.readline() assert result[-1] == "\n" return result[:-1] def _read_ints(): return map(int, _read_line().split()) def process_queries(sequence, queries): sequence = tuple(sequence) indices_by_values = defaultdict(list) for i, x in enumerate(sequence): indices_by_values[x].append(i) enumerated_queries = sorted(enumerate(queries), key=lambda iv: iv[1][0])[::-1] queries_responses = [None] * len(enumerated_queries) selections_tree = [0] * (len(sequence) + 1) k = 0 for value, indices in sorted(indices_by_values.items(), reverse=True): for index_to_select in indices: _fenwick_tree_add(selections_tree, index_to_select, 1) k += 1 while enumerated_queries and enumerated_queries[-1][1][0] == k: query_index, (_k, subseq_index) = enumerated_queries.pop() seq_index = _find_seq_index_by_subseq_index(selections_tree, subseq_index) queries_responses[query_index] = sequence[seq_index] return queries_responses def _find_seq_index_by_subseq_index(tree, subseq_i): min_i = 0 max_i = len(tree) - 1 while min_i != max_i: mid_i = (min_i + max_i) // 2 if _fenwick_tree_prefix_sum(tree, mid_i) < subseq_i: min_i = mid_i + 1 else: max_i = mid_i return min_i def _fenwick_tree_prefix_sum(tree, i): i += 1 result = 0 while i != 0: result += tree[i] i -= i & (-i) return result def _fenwick_tree_add(tree, i, x): i += 1 while i < len(tree): tree[i] += x i += i & (-i) if __name__ == '__main__': main() ```
output
1
18,634
12
37,269
Provide tags and a correct Python 3 solution for this coding contest problem. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10].
instruction
0
18,635
12
37,270
Tags: data structures, greedy Correct Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase class SortedList: def __init__(self, iterable=None, _load=200): """Initialize sorted list instance.""" if iterable is None: iterable = [] 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 main(): n=int(input()) aa=list(map(int,input().split())) a=[(v,n-i-1) for i,v in enumerate(aa)] a.sort() a.reverse() q=[] for i in range(int(input())): x,y=map(int,input().split()) q.append((x,y,i)) q.sort(key=lambda x:x[0]) b=SortedList() ans=[0]*(len(q)) j=0 for i in q: while j<i[0]: b.add(-(a[j][1]-n+1)) j+=1 ans[i[2]]=aa[b[i[1]-1]] for i in ans: print(i) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
output
1
18,635
12
37,271
Provide tags and a correct Python 3 solution for this coding contest problem. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10].
instruction
0
18,636
12
37,272
Tags: data structures, greedy Correct Solution: ``` class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class OrderedList(SortedList): #Codeforces, Ordered Multiset def __init__(self, arg): super().__init__(arg) def rangeCountByValue(self, leftVal, rightVal): #returns number of items in range [leftVal,rightVal] inclusive leftCummulative = self.bisect_left(leftVal) rightCummulative = self.bisect_left(rightVal + 1) return rightCummulative - leftCummulative def main(): # m(logn) solution n=int(input()) a=readIntArr() indexes=list(range(n)) indexes.sort(key=lambda i:(-a[i],i)) # sort by a[i] desc then i asc ol=OrderedList([]) m=int(input()) queries=[] for i in range(m): k,pos=readIntArr() queries.append([k,pos,i]) queries.sort() # sort by k asc ans=[-1]*m j=0 for k,pos,i in queries: while j<=k-1: ol.add(indexes[j]) j+=1 ans[i]=a[ol[pos-1]] multiLineArrayPrint(ans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(i,j): print('? {} {}'.format(i,j)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(' '.join([str(x) for x in ans]))) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 for _abc in range(1): main() ```
output
1
18,636
12
37,273
Provide tags and a correct Python 3 solution for this coding contest problem. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10].
instruction
0
18,637
12
37,274
Tags: data structures, greedy Correct Solution: ``` WIDTH = 10 def index_tree(n): levels = [ [1]*n ] size = WIDTH while size < n: m, r = n // size, n % size levels.append( [size]*m + ([r] if r > 0 else []) ) size *= WIDTH return levels def dec_index(levels, i): for level in levels: level[i] -= 1 i //= WIDTH def find_pos(levels, pos): i, l = 0, len(levels) - 1 total = 0 while True: level = levels[l] while total + level[i] < pos: total += level[i] i += 1 if l == 0: return i i *= WIDTH l -= 1 import sys def main(): ## INPUT numbers = [int(x) for x in sys.stdin.read().split()] n = numbers[0] sequence = numbers[1:n+1] m = numbers[n+1] queries = {} for i in range(n+2, n+2 + 2*m, 2): k, pos = numbers[i], numbers[i+1] if k in queries: queries[k][pos] = None else: queries[k] = { pos: None } ## WORK sequence1 = sorted([ (s,-i) for i,s in enumerate(sequence) ]) tree = index_tree(n) size = n for _, neg_i in sequence1: if size in queries: for pos in queries[size]: queries[size][pos] = find_pos(tree, pos) dec_index(tree, -neg_i) size -= 1 ## PRINT for i in range(n+2, n+2 + 2*m, 2): k, pos = numbers[i], numbers[i+1] print(sequence[ queries[k][pos] ]) main() ```
output
1
18,637
12
37,275
Provide tags and a correct Python 3 solution for this coding contest problem. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10].
instruction
0
18,638
12
37,276
Tags: data structures, greedy Correct Solution: ``` import sys class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n if __name__ == '__main__': lines = sys.stdin.readlines() n = int(lines[0]) aa = [(a, i) for i, a in enumerate(map(int, lines[1].split()))] m = int(lines[2]) qs = [None]*m ans = [None]*m for i in range(m): k, pos = map(int, lines[i+3].split()) qs[i] = (pos, k, i) qs.sort(key=lambda x: x[1]) aa.sort(key=lambda x: x[1]) aa.sort(key=lambda x: x[0], reverse=True) avl = AvlTree() s = 0 for pos, k, i in qs: for a, j in aa[s: k]: avl.add(j, a) ans[i] = str(avl.get_at(pos - 1)[1]) s = k print("\n".join(ans)) ```
output
1
18,638
12
37,277
Provide tags and a correct Python 3 solution for this coding contest problem. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10].
instruction
0
18,639
12
37,278
Tags: data structures, greedy Correct Solution: ``` """ Author - Satwik Tiwari . 18th Feb , 2021 - Thursday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt,log2 from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def testcase(t): for pp in range(t): solve(pp) def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = 10**9+7 #=============================================================================================== # code here ;)) class FenwickTree: def __init__(self, x): """transform list into BIT""" self.bit = x for i in range(len(x)): j = i | (i + 1) if j < len(x): x[j] += x[i] def update(self, idx, x): """updates bit[idx] += x""" while idx < len(self.bit): self.bit[idx] += x idx |= idx + 1 def query(self, end): """calc sum(bit[:end))""" x = 0 while end: x += self.bit[end - 1] end &= end - 1 return x def findkth(self, k): """Find largest idx such that sum(bit[:idx]) <= k""" idx = -1 for d in reversed(range(len(self.bit).bit_length())): right_idx = idx + (1 << d) if right_idx < len(self.bit) and k >= self.bit[right_idx]: idx = right_idx k -= self.bit[idx] return idx + 1 def printpref(self): out = [] for i in range(1,len(self.bit) + 1): out.append(self.query(i)) print(out) """ ask query(i+1) ---->>> 1 indexed based update(i,x) --->>> 0indexed based """ 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(case): n = int(inp()) a = lis() queries = [] m = int(inp()) for i in range(m): k,pos = sep() queries.append((k,pos,i)) queries.sort() b = sorted(a)[::-1] ind = {} for i in range(n): if(a[i] not in ind): ind[a[i]] = deque([i]) else: ind[a[i]].append(i) # currind = 0 # bit = FenwickTree([0]*(len(a) + 10)) # ans = [-1]*m # for k,pos,where in queries: # while(currind < k): # print(b[currind],'========') # bit.update(ind[b[currind]].popleft(),1) # currind+=1 # print(where,'==',bit.findkth(pos-1),pos) # ans[where] = (bit.findkth(pos-1) + 1) # print(bit.printpref()) # # for i in ans: # print(a[i]) sl = SortedList() currind = 0 ans = [-1]*m for k,pos,where in queries: while(currind < k): sl.add(ind[b[currind]].popleft()) currind += 1 ans[where] = a[sl[pos-1]] for i in ans: print(i) testcase(1) # testcase(int(inp())) ```
output
1
18,639
12
37,279
Provide tags and a correct Python 3 solution for this coding contest problem. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10].
instruction
0
18,640
12
37,280
Tags: data structures, greedy Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n avl=AvlTree() #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', func=lambda a, b: min(a ,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a * a + b * b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left)/ 2) # Check if middle element is # less than or equal to key if (arr[mid]<=key): count = mid+1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def countGreater( n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) print(m,avl.get_at(m)[0]) if (avl.get_at(m)[0] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n=int(input()) l=list(map(int,input().split())) d=dict() for i in range(n): if l[i] in d: d[l[i]].append(i) else: d.update({l[i]:deque([i])}) rt=[]+l l.sort(reverse=True) ind1=[0]*n for i in range(n): ind1[i]=d[l[i]][0] d[l[i]].popleft() q=int(input()) a=[0]*q b=[0]*q d=dict() for i in range(q): a[i],b[i]=map(int,input().split()) if a[i] in d: d[a[i]].append(b[i]) else: d.update({a[i]:[b[i]]}) c=-1 ans=dict() for i in sorted(d.keys()): for j in sorted(d[i]): ai=i bi=j while(c<ai-1): c+=1 avl.add(ind1[c],ind1[c]) ans.update({(ai,bi):rt[avl.get_at(bi-1)[0]]}) for i in range(q): print(ans[(a[i],b[i])]) ```
output
1
18,640
12
37,281
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` import sys input = sys.stdin.buffer.readline mx = 2*10**5 + 1 bit = [0]*(mx) def add(idx): idx += 1 while idx < mx: bit[idx] += 1 idx += idx & - idx # log(n) !!! def lower_bound(val): pos = 0 tot = 0 for i in range(20,-1,-1): if pos + (1 << i) < mx and tot + bit[pos + (1 << i)] < val: tot += bit[pos + (1 << i)] pos += (1 << i) return pos n = int(input()) a = list(map(int,input().split())) new_el = sorted(list(range(n)), key = lambda i: (-a[i], i)) m = int(input()) queries = [] answers = [0]*m for i in range(m): k,p = map(int,input().split()) queries.append([k,p,i]) queries.sort() curr_len = 0 for i in range(m): k,pos,query_idx = queries[i] while curr_len < k: add(new_el[curr_len]) curr_len += 1 answers[query_idx] = a[lower_bound(pos)] print(*answers) ```
instruction
0
18,641
12
37,282
Yes
output
1
18,641
12
37,283
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- 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") # -------------------game starts now----------------------------------------------------import math class Node: def __init__(self, key): self.left = None self.right = None self.val = key # A utility function to insert a new node with the given key def insert(root, node): if root is None: root = node else: if root.val < node.val: if root.right is None: root.right = node else: insert(root.right, node) else: if root.left is None: root.left = node else: insert(root.left, node) def search(root, key): if root is None or root.val == key: return root # Key is greater than root's key if root.val < key: return search(root.right, key) # Key is smaller than root's key return search(root.left, key) def KSmallestUsingMorris(root, k): count = 0 ksmall = -9999999999 curr = root while curr != None: if curr.left == None: count += 1 if count == k: ksmall = curr.val curr = curr.right else: pre = curr.left while (pre.right != None and pre.right != curr): pre = pre.right if pre.right == None: pre.right = curr curr = curr.left else: pre.right = None count += 1 if count == k: ksmall = curr.val curr = curr.right return ksmall def minValueNode(node): current = node while (current.left is not None): current = current.left return current def deleteNode(root, key): if root is None: return root if key < root.val: root.left = deleteNode(root.left, key) elif (key > root.val): root.right = deleteNode(root.right, key) else: if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp temp = minValueNode(root.right) root.key = temp.val root.right = deleteNode(root.right, temp.val) return root #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', func=lambda a, b: min(a ,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a * a + b * b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left)/ 2) # Check if middle element is # less than or equal to key if (arr[mid]<=key): count = mid+1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) # If mid element is greater than # k update leftGreater and r if (arr[m] > k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n=int(input()) l=list(map(int,input().split())) d=dict() for i in range(n): if l[i] in d: d[l[i]].append(i) else: d.update({l[i]:deque([i])}) rt=[]+l l.sort(reverse=True) ind1=[0]*n for i in range(n): ind1[i]=d[l[i]][0] d[l[i]].popleft() q=int(input()) a=[0]*q b=[0]*q inw=dict() for i in range(q): a[i],b[i]=map(int,input().split()) inw.update({(a[i],b[i]):i}) b=sort_list(b,a) a.sort() ind=[0]*q for i in range(q): ind[i]=inw[(a[i],b[i])] a.sort() c=0 ans=[0]*q r=Node(-99999999) for i in range(len(a)): while(c<a[i]): insert(r,Node(ind1[c])) c+=1 #print(KSmallestUsingMorris(r,b[i]+1)) ans[i]=rt[KSmallestUsingMorris(r,b[i]+1)] ans=sort_list(ans,ind) print(*ans,sep="\n") ```
instruction
0
18,642
12
37,284
No
output
1
18,642
12
37,285
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the harder version of the problem. In this version, 1 ≀ n, m ≀ 2β‹…10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 ≀ k ≀ n) is given, then the subsequence is called optimal if: * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≀ t ≀ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: * [10, 20, 20] lexicographically less than [10, 21, 1], * [7, 99, 99] is lexicographically less than [10, 21, 1], * [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j. For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β€” it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30. Input The first line contains an integer n (1 ≀ n ≀ 2β‹…10^5) β€” the length of the sequence a. The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). The third line contains an integer m (1 ≀ m ≀ 2β‹…10^5) β€” the number of requests. The following m lines contain pairs of integers k_j and pos_j (1 ≀ k ≀ n, 1 ≀ pos_j ≀ k_j) β€” the requests. Output Print m integers r_1, r_2, ..., r_m (1 ≀ r_j ≀ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j. Examples Input 3 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 Output 20 10 20 10 20 10 Input 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 Output 2 3 2 3 2 3 1 1 3 Note In the first example, for a=[10,20,10] the optimal subsequences are: * for k=1: [20], * for k=2: [10,20], * for k=3: [10,20,10]. Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- class FenwickTree: def __init__(self, x): """transform list into BIT""" self.bit = x for i in range(len(x)): j = i | (i + 1) if j < len(x): x[j] += x[i] def update(self, idx, x): """updates bit[idx] += x""" while idx < len(self.bit): self.bit[idx] += x idx |= idx + 1 def query(self, end): """calc sum(bit[:end])""" x = 0 while end: x += self.bit[end - 1] end &= end - 1 return x def findkth(self, k): """Find largest idx such that sum(bit[:idx]) <= k""" idx = -1 for d in reversed(range(len(self.bit).bit_length())): right_idx = idx + (1 << d) if right_idx < len(self.bit) and k >= self.bit[right_idx]: idx = right_idx k -= self.bit[idx] return idx + 1 #------------------------------------------------------------------------ from collections import deque def main(): n=int(input()) vals=list(map(int,input().split())) sorts=[(vals[s],s) for s in range(n)] sorts.sort(key=lambda x: [x[0],-x[1]]) print(sorts) sorts=deque(sorts) BIT=FenwickTree([1]*n) #ok i think i got it m=int(input());quer=[] for s in range(m): k,pos=map(int,input().split()) quer.append((k,pos)) dict1={};new=quer.copy() new.sort(key=lambda x: x[0]) k=n while k>0: if len(new)>0: while len(new)>0 and new[-1][0]==k: v0=new.pop() shift=BIT.findkth(v0[1]) ans=vals[shift-1] dict1[v0]=ans k-=1 v1=sorts.popleft() BIT.update(v1[1]+1,-1) else: break for s in range(m): query=quer[s] print(dict1[query]) main() ```
instruction
0
18,643
12
37,286
No
output
1
18,643
12
37,287
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0.
instruction
0
18,756
12
37,512
Tags: brute force, greedy, implementation Correct Solution: ``` n, q = map(int, input().split()) arr = list(map(int, input().split())) count = sum(arr) answer = "" for _ in range(q): t, kx = map(int, input().split()) if t == 1: arr[kx-1] = 1 - arr[kx-1] if arr[kx-1]: count += 1 else: count -= 1 else: if count < kx: answer += "0" else: answer += "1" for i in answer: print(i) ```
output
1
18,756
12
37,513
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0.
instruction
0
18,757
12
37,514
Tags: brute force, greedy, implementation Correct Solution: ``` x,y=0,0 n, q = map(int, input().split()) a = list(map(int, input().split())) for i in range(n): if a[i]==0: x+=1 else: y+=1 for i in range(q): t, m = map(int, input().split()) if t == 1: if a[m-1]==1: a[m-1]=0 x=x+1 y=y-1 elif a[m-1]==0: a[m-1]=1 x=x-1 y=y+1 elif t == 2: if m>y: print (0) else: print (1) ```
output
1
18,757
12
37,515
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0.
instruction
0
18,758
12
37,516
Tags: brute force, greedy, implementation Correct Solution: ``` n,q=map(int,input().split()) a=list(map(int,input().split())) s=sum(a) for i in range(q): h,k=map(int,input().split()) if h==1: y=a[k-1] if y==1: s-=1 else: s+=1 a[k-1]=1-a[k-1] else: if s>=k: print(1) else: print(0) ```
output
1
18,758
12
37,517
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0.
instruction
0
18,759
12
37,518
Tags: brute force, greedy, implementation Correct Solution: ``` # cook your dish here n,q = map(int,input().split()) a = [int(x) for x in input().split()] d = {0:0,1:0} for i in a: d[i]+=1 for _ in range(q): x,y = map(int,input().split()) if x==1: y-=1 d[a[y]]-=1 a[y] = 1 - a[y] d[a[y]] += 1 else: if d[1]>=y: print(1) else: print(0) ```
output
1
18,759
12
37,519
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0.
instruction
0
18,760
12
37,520
Tags: brute force, greedy, implementation Correct Solution: ``` #author: anshul_129 from sys import stdin, stdout, maxsize from math import sqrt, log, factorial as ft, gcd from collections import defaultdict as D, OrderedDict as OD from bisect import insort n, q = map(int, stdin.readline().strip().split()) #s = stdin.readline().strip() a = list(map(int, stdin.readline().strip().split())) #b = list(map(int, stdin.readline().strip().split())) ones = sum(a) for i in range(q): t, x = map(int, stdin.readline().strip().split()) if t == 1: if a[x - 1]: a[x - 1] = 0 ones -= 1 else: a[x - 1] = 1 ones += 1 else: if ones >= x: print(1) else: print(0) ```
output
1
18,760
12
37,521
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0.
instruction
0
18,761
12
37,522
Tags: brute force, greedy, implementation Correct Solution: ``` import math def getint(): return [int(i) for i in input().split()] def getstr(): return [str(i) for i in input().split()] #-------------------------------------------------------------------------- def solve(): n,q=getint() a=getint() ans=a.count(1) for i in range(q): t,s=getint() if t==1: if a[s-1]==1: ans-=1 else: ans+=1 a[s-1]=1-a[s-1] else: if ans>=s: print(1) else: print(0) #-------------------------------------------------------------------------- #for _ in range(int(input())): solve() ```
output
1
18,761
12
37,523
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0.
instruction
0
18,762
12
37,524
Tags: brute force, greedy, implementation Correct Solution: ``` one = 0 def assign(m): global one if a[m-1] == 1: a[m-1] = 0 one = one-1 else: a[m-1] = 1 one = one+1 def show(n): if n <= one: print("1") else: print("0") n, q = [int(g) for g in input().split()] a = [int(h) for h in input().split()] for item in a: if item == 1: one += 1 for i in range(q): t, x = [int(j) for j in input().split()] if t == 1: assign(x) if t == 2: show(x) ```
output
1
18,762
12
37,525
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0.
instruction
0
18,763
12
37,526
Tags: brute force, greedy, implementation Correct Solution: ``` #!/usr/bin/env python from __future__ import division, print_function import math import os import sys from sys import stdin,stdout from io import BytesIO, IOBase from collections import deque #sys.setrecursionlimit(10**5) if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #----------------------------------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count def regularbracket(t): p=0 for i in t: if i=="(": p+=1 else: p-=1 if p<0: return False else: if p>0: return False else: return True # endregion """ def samesign(a,b): if (a>0 and b>0) or (a<0 and b<0): return True return False def main(): t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int,input().split())) sum1=0 l=[arr[0]] for i in range(len(arr)-1): if samesign(arr[i+1],arr[i])==True: l.append(arr[i+1]) else: # print(l) # print(max(l)) sum1+=max(l) l=[arr[i+1]] #print(sum1) # print(l) sum1+=max(l) print(sum1) """ """ def main(): t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int,input().split())) sum1 = sum(arr) # max1 = max(arr) arr = sorted(arr) flag = True for i in range(1,n+1): if arr[i-1]>i: print("second") flag = False break if flag==True: diff = (n*(n+1))/2-sum1 if diff%2==0: print("Second") else: print("First") """ """ def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) seg = [0] * (n + 1) curr = 0 cnt = 0 for ai in a: if ai == curr: cnt += 1 else: if cnt > 0: seg[curr] += 1 curr = ai cnt = 1 if cnt > 0: seg[curr] += 1 res = n for i in range(1, n + 1): if seg[i] == 0: continue op = seg[i] + 1 if i == a[0]: op -= 1 if i == a[-1]: op -= 1 res = min(res, op) print((res)) """ """ def main(): t = int(input()) for _ in range(t): a,b = map(int,input().split()) if a==0 or b==0: print(0) elif a>=2*b or b>=2*a: print(min(a,b)) else: print((a+b)//3) """ """ def main(): t = int(input()) for _ in range(t): n, m, x, y = map(int, input().split()) ans = 0 y = min(y, 2 * x) for i_ in range(n): s = input() i = 0 while i < m: if s[i] == '*': i += 1 continue j = i while j + 1 < m and s[j + 1] == '.': j += 1 l = j - i + 1 ans += l % 2 * x + l // 2 * y i = j + 1 print(ans) """ """ def main(): t = int(input()) for _ in range(t): n,x = map(int,input().split()) arr = list(map(int,input().split())) p=0 sum1 = sum(arr) arr = sorted(arr) if sum1//n>=x: print(n) else: for i in range(n-1): sum1-=arr[i] if sum1//(n-(i+1))>=x: print(n-(i+1)) break else: print(0) """ """ def main(): p = int(input()) for _ in range(p): n,k = map(int,input().split()) list1=[] if n==1 and k==1: print(0) else: for i in range(n,0,-1): if i+(i-1)<=k: list1.append(i) break else: list1.append(i) list1.remove(k) print(len(list1)) print(*list1) """ """ def mirrortime(s): s = list(s) pp="" for i in range(len(s)): if s[i]=="0": continue elif s[i]=="2": s[i]="5" elif s[i]=="5": s[i]="2" elif i=="8": continue elif i=="1": continue for i in s: pp+=i return pp #print(mirrortime("2255")) def main(): t = int(input()) for _ in range(t): l=[3,4,6,7,9] h,m = map(int,input().split()) s = input() t=s[0:2] p=s[3:5] ll=[] mm=[] t = int(t) p = int(p) # print(t,p) for i in range(t,h): for j in range(p,m): i = str(i) if len(i)==1: i="0"+i j = str(j) if len(j)==1: j="0"+j if int(i[0]) in l or int(i[1]) in l or int(j[0]) in l or int(j[1]) in l: continue else: ll.append(i) mm.append(j) p=0 # print(ll,mm) if len(ll)>=1: for i in range(len(ll)): cccc = ll[i] dddd = mm[i] ccc = mirrortime(cccc) ddd = mirrortime(dddd) ccc = list(ccc) ddd = list(ddd) ccc.reverse() ddd.reverse() ppp="" qqq="" for k in ccc: ppp+=k for k_ in ddd: qqq+=k_ if int(qqq)<h and int(ppp)<m: # print(int(qqq)) # print(int(ppp)) print(cccc+":"+dddd) break else: print("00:00") else: print("00:00") """ def main(): n,q = map(int,input().split()) arr = list(map(int,input().split())) c1 = arr.count(1) for i in range(q): t,query = map(int,input().split()) if t==2: if c1>=query: print(1) else: print(0) else: if arr[query-1]==1: c1-=1 else: c1+=1 arr[query-1]= 1 - arr[query-1] if __name__ == '__main__': main() ```
output
1
18,763
12
37,527
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 integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0. Submitted Solution: ``` n, q = map(int, input().split()) w = list(map(int, input().split())) e = w.count(1) for i in range(q): t, x = map(int, input().split()) if t == 1: w[x - 1] = 1 - w[x - 1] if w[x - 1] == 1: e += 1 else: e -= 1 else: print(int(e >= x)) ```
instruction
0
18,764
12
37,528
Yes
output
1
18,764
12
37,529
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 integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0. Submitted Solution: ``` n,q=map(int,input().split());lis=list(map(int,input().split()));one=lis.count(1) for i in range(q): a,b=map(int,input().split()) if a==1:lis[b-1]=1-lis[b-1];one = (one - 1 if not lis[b-1] else one + 1) else:(print(1) if one>=b else print(0)) ```
instruction
0
18,765
12
37,530
Yes
output
1
18,765
12
37,531
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 integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0. Submitted Solution: ``` n,q=map(int,input().split()) l=list(map(int,input().split())) s=0 for k in l: if k==1: s=s+1 for j in range(q): az,m=map(int,input().split()) if az==1: if l[m-1]==1: s=s-1 l[m-1]=0 else: l[m-1]=1 s=s+1 else: if m>s: print(0) else: print(1) ```
instruction
0
18,766
12
37,532
Yes
output
1
18,766
12
37,533
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 integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0. Submitted Solution: ``` n,q = map(int,input().split()) a = list(map(int,input().split())) count = a.count(1) for i in range(q): t,l = map(int,input().split()) if t == 1: if a[l-1] == 0: a[l-1] = 1 count += 1 else: a[l-1] = 0 count -= 1 else: if l>count: print(0) else: print(1) ```
instruction
0
18,767
12
37,534
Yes
output
1
18,767
12
37,535
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 integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0. Submitted Solution: ``` n,r=[int(k) for k in input().split()] a=[int(k) for k in input().split()] z=0 o=0 for ele in a: if ele==0: z+=1 else: o+=1 for i in range(r): t,x=[int(k) for k in input().split()] if t==1: if a[x-1]==0: z-=1 o+=1 else: z+=1 o-=1 if t==2: if x<=o: print(1) else: print(0) ```
instruction
0
18,768
12
37,536
No
output
1
18,768
12
37,537
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 integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0. Submitted Solution: ``` import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return (int(input())) def inlt(): return (list(map(int, input().split()))) def insr(): s = input() return (list(s[:len(s) - 1])) def invr(): return (map(int, input().split())) import math class Solution: def solve(self, t,p): if t==1: tmp = arr[p - 1] arr[p-1]=1-arr[p-1] if arr[p-1] not in idx_dic: idx_dic[arr[p-1]] = len(arr)-1 sorted_arr[-1] = arr[p - 1] else: sorted_arr[idx_dic[tmp]] = arr[p - 1] if idx_dic[tmp]>0: idx_dic[tmp]-=1 else: return sorted_arr[p-1] # t = inp() A = Solution() # arr_ = invr() # arr = list(arr_) # n, q, k = arr[0], arr[1], arr[2] # # array_ = invr() # array = list(array_) n, q = invr() arr = inlt() sorted_arr = sorted(arr, reverse=True) idx_dic={} idx_dic[1]=len(sorted_arr)-1 flag = False for i in range(1, len(sorted_arr)): if sorted_arr[i-1] != sorted_arr[i]: idx_dic[1]=i-1 idx_dic[0] = len(arr)-1 flag = True break if not flag: idx_dic.pop(1) idx_dic[0] = len(sorted_arr) - 1 for i in range(q): t,p =invr() if t==2: print(A.solve(t,p)) else: A.solve(t, p) ```
instruction
0
18,769
12
37,538
No
output
1
18,769
12
37,539
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 integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0. Submitted Solution: ``` def largest(m,n): a = list(map(int,input().split())) a.sort() a.reverse() for _ in range(n): t,x = map(int,input().split()) if t==2: print(a[x-1]) elif t==1: a[x-1] = 1-a[x-1] a,b = map(int,input().split()) largest(a,b) ```
instruction
0
18,770
12
37,540
No
output
1
18,770
12
37,541
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 integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: * Sort the array in the non-increasing order, return k-th element from it. For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1. Input The first line contains two integers n and q (1 ≀ n, q ≀ 10^5) β€” the length of the given array and the number of queries. The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≀ a_i ≀ 1) β€” elements of the initial array. Each of the following q lines contains two integers. The first integer is t (1 ≀ t ≀ 2) β€” the type of query. * If t = 1 the second integer is x (1 ≀ x ≀ n) β€” the position of the modified number. You have to assign to a_x the value 1 - a_x. * If t = 2 the second integer is k (1 ≀ k ≀ n) β€” you need to print the k-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying t = 2). Output For each query of the second type, print a single integer β€” the answer to the query. Example Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 Note Initially a = [1, 1, 0, 1, 0]. The first operation is printing the third largest value, which is 1. The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0]. The third operation is printing the third largest value, it is 0. The fourth operation is printing the first largest value, it is 1. The last operation is printing the fifth largest value, it is 0. Submitted Solution: ``` from sys import stdin, stdout from collections import Counter outputs = [] n, q = map(int, stdin.readline().strip().split()) arr = [int(num) for num in stdin.readline().strip().split()] req = Counter(arr) for __ in range(q): x, k = map(int, stdin.readline().strip().split()) if x == 1: if arr[x-1] == 1: req[1] -= 1 req[0] = req.get(0, 0) + 1 else: req[1] = req.get(1, 0) + 1 req[0] -= 1 arr[x-1] = 1 - arr[x-1] else: if k > req.get(1, 0): outputs.append(0) else: outputs.append(1) for output in outputs: stdout.write(f'{output}\n') ```
instruction
0
18,771
12
37,542
No
output
1
18,771
12
37,543
Provide tags and a correct Python 3 solution for this coding contest problem. This is the hard version of the problem. The only difference is that in this version 1 ≀ q ≀ 10^5. You can make hacks only if both versions of the problem are solved. There is a process that takes place on arrays a and b of length n and length n-1 respectively. The process is an infinite sequence of operations. Each operation is as follows: * First, choose a random integer i (1 ≀ i ≀ n-1). * Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer). See notes for an example of an operation. It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b. You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 ≀ a_i ≀ c_i for 1 ≀ i ≀ n. Your task is to count the number of good arrays a where F(a, b) β‰₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7. Input The first line contains a single integer n (2 ≀ n ≀ 100). The second line contains n integers c_1, c_2 …, c_n (0 ≀ c_i ≀ 100). The third line contains n-1 integers b_1, b_2, …, b_{n-1} (0 ≀ b_i ≀ 100). The fourth line contains a single integer q (1 ≀ q ≀ 10^5). The fifth line contains q space separated integers x_1, x_2, …, x_q (-10^5 ≀ x_i ≀ 10^5). Output Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β‰₯ x_i modulo 10^9+7. Example Input 3 2 3 4 2 1 5 -1 0 1 -100000 100000 Output 56 28 4 60 0 Note The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample). Examples of arrays a that are not good: * a = [3, 2, 3] is not good because a_1 > c_1; * a = [0, -1, 3] is not good because a_2 < 0. One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0. Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
instruction
0
18,788
12
37,576
Tags: dp, math Correct Solution: ``` def solve(): MOD = 10**9+7 n = int(input()) c = list(map(int, input().split())) b = [0] + list(map(int, input().split())) q = int(input()) queries = list(map(int, input().split())) maxans = 1 for c1 in c: maxans = maxans * (c1+1) % MOD ans = {} for i in range(1, n): b[i] += b[i-1] s = lb = 0 for i in range(1, n): s -= b[i] lb = min(lb, s//(i+1)) s = ub = c[0] for i in range(n): s += c[i] - b[i] ub = min(ub, s//(i+1)) for x in queries: if x <= lb: print(maxans) elif x > ub: print(0) elif x in ans: print(ans[x]) else: dp0 = [1] * 10002 dp0[0] = 0 bd = 0 for i in range(n): dp1 = [0] * 10002 bd += b[i] + x for j in range(max(bd, 0), 10001): dp1[j+1] = (dp1[j] + dp0[j+1] - dp0[max(j-c[i], 0)]) % MOD dp0 = dp1[:] a = dp0[-1] ans[x] = a print(a) import sys input = lambda: sys.stdin.readline().rstrip() solve() ```
output
1
18,788
12
37,577
Provide tags and a correct Python 2 solution for this coding contest problem. You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine. We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 106). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ 2bi ≀ 109). Output Print a single integer β€” the answer to the problem. Examples Input 5 3 8 4 3 2 2 3 2 2 Output 2 Input 10 6 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 Output 6 Note In the first example you are given memory clusters with sizes 8, 4, 3, 2, 2 and arrays with sizes 8, 4, 4. There are few ways to obtain an answer equals 2: you can locate array with size 8 to the cluster with size 8, and one of the arrays with size 4 to the cluster with size 4. Another way is to locate two arrays with size 4 to the one cluster with size 8. In the second example you are given 10 memory clusters with size 1 and 6 arrays with size 1. You can choose any 6 clusters and locate all given arrays to them.
instruction
0
18,850
12
37,700
Tags: binary search, bitmasks, greedy Correct Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') def pr_arr(arr): for i in arr: stdout.write(str(i)+' ') stdout.write('\n') range = xrange # not for python 3.0+ # main code n,m=in_arr() l=in_arr() d1=Counter(in_arr()) d=Counter() for i in l: for j in range(30): if (1<<j)&i: d[j]+=1 for i in range(28,-1,-1): d[i]+=2*d[i+1] ans=0 for i in range(30): ans+=min(d1[i],d[i]) d[i+1]=min(max(0,d[i]-d1[i])/2,d[i+1]) pr_num(ans) ```
output
1
18,850
12
37,701
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine. We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 106). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ 2bi ≀ 109). Output Print a single integer β€” the answer to the problem. Examples Input 5 3 8 4 3 2 2 3 2 2 Output 2 Input 10 6 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 Output 6 Note In the first example you are given memory clusters with sizes 8, 4, 3, 2, 2 and arrays with sizes 8, 4, 4. There are few ways to obtain an answer equals 2: you can locate array with size 8 to the cluster with size 8, and one of the arrays with size 4 to the cluster with size 4. Another way is to locate two arrays with size 4 to the one cluster with size 8. In the second example you are given 10 memory clusters with size 1 and 6 arrays with size 1. You can choose any 6 clusters and locate all given arrays to them. Submitted Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') def pr_arr(arr): for i in arr: stdout.write(str(i)+' ') stdout.write('\n') range = xrange # not for python 3.0+ # main code n,m=in_arr() l=in_arr() d1=Counter(in_arr()) d=Counter() for i in l: for j in range(30): if (1<<j)&i: d[j]+=1 ans=0 for i in d1: ans+=min(d1[i],d[i]) pr_num(ans) ```
instruction
0
18,851
12
37,702
No
output
1
18,851
12
37,703
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine. We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 106). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ 2bi ≀ 109). Output Print a single integer β€” the answer to the problem. Examples Input 5 3 8 4 3 2 2 3 2 2 Output 2 Input 10 6 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 Output 6 Note In the first example you are given memory clusters with sizes 8, 4, 3, 2, 2 and arrays with sizes 8, 4, 4. There are few ways to obtain an answer equals 2: you can locate array with size 8 to the cluster with size 8, and one of the arrays with size 4 to the cluster with size 4. Another way is to locate two arrays with size 4 to the one cluster with size 8. In the second example you are given 10 memory clusters with size 1 and 6 arrays with size 1. You can choose any 6 clusters and locate all given arrays to them. Submitted Solution: ``` n, m = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) b = [2**i for i in b] a.sort(reverse=True) b.sort(reverse=True) ans = 0 for i in range(len(b)): if b[i] > a[i]: break ans+=1 print(ans) ```
instruction
0
18,852
12
37,704
No
output
1
18,852
12
37,705
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.
instruction
0
18,949
12
37,898
Tags: sortings Correct Solution: ``` na,nb=map(int,input().split()) k,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) temp=a[k-1] for j in b: if j>temp: l=b.index(j) break try: if nb-l>=m: print('YES') else: print('NO') except: print('NO') ```
output
1
18,949
12
37,899
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.
instruction
0
18,950
12
37,900
Tags: sortings Correct Solution: ``` n,m = map(int,input().split(' ')) a,b = map(int,input().split(' ')) arr1 = [int(i) for i in input().split(' ')] arr2 = [int(i) for i in input().split(' ')] if(arr1[a-1] < arr2[m-b]): print('YES') else: print('NO') ```
output
1
18,950
12
37,901
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.
instruction
0
18,951
12
37,902
Tags: sortings Correct Solution: ``` a,b=map(int,input().split()) k,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() b.sort() a=a[:k] b=b[-m:] if(a[-1]>=b[0]): print("NO") else: print("YES") ```
output
1
18,951
12
37,903
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.
instruction
0
18,952
12
37,904
Tags: sortings Correct Solution: ``` n, m = map(int, input().split()) k1, k2 = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) if a[k1 - 1] < b[m - k2]: print('YES') else: print('NO') ```
output
1
18,952
12
37,905
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.
instruction
0
18,953
12
37,906
Tags: sortings Correct Solution: ``` #!/usr/bin/env python3 import sys NA, NB = input().split() K, M = input().split() K, M = int(K), int(M) A = list(map(int, input().split())) B = list(map(int, input().split())) if (A[K-1] < B[-M]): print('YES') else: print('NO') ```
output
1
18,953
12
37,907
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.
instruction
0
18,954
12
37,908
Tags: sortings Correct Solution: ``` # (1 ≀ nA, nB  ≀ 10^5) number_array_a , number_array_b = map(int,input().split()) # (1 ≀ k ≀ nA, 1 ≀ m ≀ nB) k , m = map(int,input().split()) # Array A ( - 10^9  ≀  a1  ≀  a2  ≀ ... ≀  anA  ≀  10^9), sorted in non-decreasing order array_a = list(map(int,input().split())) # Array B ( - 10^9  ≀  b1  ≀  b2  ≀ ... ≀  bnB  ≀ 10^9) , sorted in non-decreasing order array_b = list(map(int,input().split())) #Get max of min elements Array A max_a = array_a[k-1] #Get min of max elements Array B min_b = array_b[-m] if max_a < min_b: print('YES') else: print('NO') ```
output
1
18,954
12
37,909
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.
instruction
0
18,955
12
37,910
Tags: sortings Correct Solution: ``` input();x,y=map(int,input().split());a=list(map(int,input().split()));b=list(map(int,input().split())) print('YES' if a[:x][-1]<b[::-1][:y][-1] else 'NO') ```
output
1
18,955
12
37,911
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.
instruction
0
18,956
12
37,912
Tags: sortings Correct Solution: ``` na, nb = [int(j) for j in input().split()] k, m = [int(j) for j in input().split()] a = [int(j) for j in input().split()] b = [int(j) for j in input().split()] if a[k - 1] < b[nb - m]: print("YES") else: print("NO") ```
output
1
18,956
12
37,913
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>. Submitted Solution: ``` x,y=[int(i) for i in input().split()] k,m=[int(i) for i in input().split()] l1=[int(o) for o in input().split()] l2=[int(u) for u in input().split()] f=l1[:k:] l2.reverse() q=l2[:m:] if max(f) <min(q): print("YES") else: print("NO") ```
instruction
0
18,957
12
37,914
Yes
output
1
18,957
12
37,915
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>. Submitted Solution: ``` def main(): s, k = map(int, input().split()) n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) if (a[n - 1] < b[-m]): print("YES") else: print("NO") main() ```
instruction
0
18,958
12
37,916
Yes
output
1
18,958
12
37,917
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>. Submitted Solution: ``` na, nb = map(int, input().split()) k, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) if a[k - 1] < b[nb - m]: print('YES') else: print('NO') ```
instruction
0
18,959
12
37,918
Yes
output
1
18,959
12
37,919
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>. Submitted Solution: ``` na, nb = map(int, input().split()) k,m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) ac = a[k-1] bc = b[len(b) - m] if (ac < bc): print("YES") else: print("NO") ```
instruction
0
18,960
12
37,920
Yes
output
1
18,960
12
37,921
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>. Submitted Solution: ``` a,b=map(int,input().split()) l,r=map(int,input().split()) v=list(map(int,input().split())) b=list(map(int,input().split())) ma=max(v[0:l]) mi=min(b[0:r]) print(["YES","NO"][ma<mi]) ```
instruction
0
18,961
12
37,922
No
output
1
18,961
12
37,923
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>. Submitted Solution: ``` #!/usr/bin/env python3 """ Codeforces Round #317 (Div. 2) Problem 572 A. Arrays @author yamaton @date 2015-08-23 """ import itertools as it import functools import operator import collections import math import sys def solve(xs, ys, k, m): return max(xs[-k:]) < min(ys[-m:]) def print_stderr(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def tf_to_yn(tf): return 'YES' if tf else 'NO' def main(): [na, nb] = [int(i) for i in input().strip().split()] [k, m] = [int(i) for i in input().strip().split()] xs = [int(i) for i in input().strip().split()] ys = [int(i) for i in input().strip().split()] assert len(xs) == na assert len(ys) == nb result = tf_to_yn(solve(xs, ys, k, m)) print(result) if __name__ == '__main__': main() ```
instruction
0
18,962
12
37,924
No
output
1
18,962
12
37,925
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>. Submitted Solution: ``` n1, n2 = map(int, input().split()) k, m = map(int, input().split()) l1 = list(map(int, input().split())) l2 = list(map(int, input().split())) def check(): i1, i2 = 0, 0 while i1 < k and i2 < m: if(l1[i1] < l2[i2]): i1 += 1 elif (l1[i1] > l2[i2]): i2 += 1 else: i1 += 1 i2 += 1 if i1 == m: return False else: return True if(check()): print("YES") else: print("NO") ```
instruction
0
18,963
12
37,926
No
output
1
18,963
12
37,927
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B. Output Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes). Examples Input 3 3 2 1 1 2 3 3 4 5 Output YES Input 3 3 3 3 1 2 3 3 4 5 Output NO Input 5 2 3 1 1 1 1 1 1 2 2 Output YES Note In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3). In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>. Submitted Solution: ``` __author__ = 'Rock' a , b=map(int , input().split()) k , m=map(int , input().split()) list1 = input().split(" ") list2 = input().split(" ") if(list1[k-1]<list2[-m]): print("YES") else: print("NO") ```
instruction
0
18,964
12
37,928
No
output
1
18,964
12
37,929
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed). Input The first line contains one integer number n (1 ≀ n ≀ 106). The second line contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one number β€” the expected number of unique elements in chosen segment. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 β€” formally, the answer is correct if <image>, where x is jury's answer, and y is your answer. Examples Input 2 1 2 Output 1.500000 Input 2 2 2 Output 1.000000
instruction
0
19,043
12
38,086
Tags: data structures, math, probabilities, two pointers Correct Solution: ``` # Accepted on Hacker blocks, giving RTE on test case 6 on Codeforces lim = 10**7 last_occ = [ 0 for i in range(lim)] n = int(input()) ans = [0 for i in range(n+1)] arr = [int(i) for i in input().split()] arr.insert(0,0 ) #print("arr",arr) for i in range(1,n+1): ans[i] = ans[i-1] + (i-last_occ[arr[i]]) last_occ[arr[i]] = i #print("ans",ans) total_sum = sum(ans) ans = round((2*(total_sum-n)+n)/n**2,6) #print(ans) print(format(ans,'.6f')) ```
output
1
19,043
12
38,087
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed). Input The first line contains one integer number n (1 ≀ n ≀ 106). The second line contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one number β€” the expected number of unique elements in chosen segment. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 β€” formally, the answer is correct if <image>, where x is jury's answer, and y is your answer. Examples Input 2 1 2 Output 1.500000 Input 2 2 2 Output 1.000000
instruction
0
19,044
12
38,088
Tags: data structures, math, probabilities, two pointers Correct Solution: ``` import sys from collections import defaultdict n = int(sys.stdin.buffer.readline().decode('utf-8')) a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split())) next_dic = defaultdict(list) for i in range(n-1, -1, -1): next_dic[a[i]].append(i) fx = sum((n-v[-1])*2 for v in next_dic.values()) ans = 0 for i in range(n): j = next_dic[a[i]].pop() ans += fx - 1 fx += -(n - j)*2 + (n - next_dic[a[i]][-1] if next_dic[a[i]] else 0)*2 print(ans / (n*n)) ```
output
1
19,044
12
38,089
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed). Input The first line contains one integer number n (1 ≀ n ≀ 106). The second line contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 106) β€” elements of the array. Output Print one number β€” the expected number of unique elements in chosen segment. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 β€” formally, the answer is correct if <image>, where x is jury's answer, and y is your answer. Examples Input 2 1 2 Output 1.500000 Input 2 2 2 Output 1.000000
instruction
0
19,045
12
38,090
Tags: data structures, math, probabilities, two pointers Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) d = {} def push(d, x, i): if x not in d: d[x]=[] d[x].append(i) for i, x in enumerate(a): push(d, x, i) S=0 for arr in d.values(): pre=-1 for i in arr: S += 2 * (i-pre)*(n-i) pre=i print((S-n)/(n*n)) ```
output
1
19,045
12
38,091