message
stringlengths
2
67k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
463
109k
cluster
float64
19
19
__index_level_0__
int64
926
217k
Provide tags and a correct Python 3 solution for this coding contest problem. The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: * each cup contains a mark β€” a number from 1 to n; all marks on the cups are distinct; * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input The first line contains integers n and m (1 ≀ n, m ≀ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≀ xi, yi ≀ n) β€” the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i. If there are multiple correct answers, you should print the lexicographically minimum one. Examples Input 2 1 2 1 Output 2 1 Input 3 2 1 2 1 1 Output 2 1 3 Input 3 3 1 3 2 3 1 3 Output -1
instruction
0
36,456
19
72,912
Tags: data structures Correct Solution: ``` import io import os # List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py class UnsortedList: 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] pass else: del _lists[pos] del _list_lens[pos] # del _mins[pos] self._rebuild = True 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 __setitem__(self, index, value): pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._lists[pos][idx] = value def insert(self, index, value): _load = self._load _lists = self._lists _list_lens = self._list_lens if _lists: pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _list_lens.append(1) self._rebuild = True self._len += 1 def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return "SortedList({0})".format(list(self)) def solve(N, M, queries): idToMark = [-1 for i in range(N)] cups = UnsortedList([i for i in range(N)]) for mark, pos in queries: pos -= 1 # 0-indexed cupId = cups[pos] del cups[pos] cups.insert(0, cupId) if idToMark[cupId] == -1: idToMark[cupId] = mark elif idToMark[cupId] != mark: return b"-1" markToCounts = [0 for i in range(N + 1)] for cupId, mark in enumerate(idToMark): if mark != -1: markToCounts[mark] += 1 if markToCounts[mark] > 1: return b"-1" j = 1 ans = [] for cupId, mark in enumerate(idToMark): if mark != -1: ans.append(mark) else: while markToCounts[j] > 0: j += 1 ans.append(j) j += 1 return b" ".join(str(x).encode("ascii") for x in ans) if False: N, M = 10 ** 6, 10 ** 6 queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)] ans = solve(N, M, queries) # print(ans) assert ans != b"-1" exit() if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, M = [int(x) for x in input().split()] queries = ((int(x) for x in input().split()) for i in range(M)) ans = solve(N, M, queries) os.write(1, ans) ```
output
1
36,456
19
72,913
Provide tags and a correct Python 3 solution for this coding contest problem. The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: * each cup contains a mark β€” a number from 1 to n; all marks on the cups are distinct; * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input The first line contains integers n and m (1 ≀ n, m ≀ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≀ xi, yi ≀ n) β€” the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i. If there are multiple correct answers, you should print the lexicographically minimum one. Examples Input 2 1 2 1 Output 2 1 Input 3 2 1 2 1 1 Output 2 1 3 Input 3 3 1 3 2 3 1 3 Output -1
instruction
0
36,457
19
72,914
Tags: data structures Correct Solution: ``` import io import os # List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py class UnsortedList: def __init__(self, iterable=[], _load=100): """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] pass else: del _lists[pos] del _list_lens[pos] # del _mins[pos] self._rebuild = True 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 __setitem__(self, index, value): pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._lists[pos][idx] = value def insert(self, index, value): _load = self._load _lists = self._lists _list_lens = self._list_lens if _lists: pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _list_lens.append(1) self._rebuild = True self._len += 1 def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return "SortedList({0})".format(list(self)) def solve(N, M, queries): idToMark = [-1 for i in range(N)] cups = UnsortedList([i for i in range(N)]) for mark, pos in queries: pos -= 1 # 0-indexed cupId = cups[pos] del cups[pos] cups.insert(0, cupId) if idToMark[cupId] == -1: idToMark[cupId] = mark elif idToMark[cupId] != mark: return b"-1" markToCounts = [0 for i in range(N + 1)] for cupId, mark in enumerate(idToMark): if mark != -1: markToCounts[mark] += 1 if markToCounts[mark] > 1: return b"-1" j = 1 ans = [] for cupId, mark in enumerate(idToMark): if mark != -1: ans.append(mark) else: while markToCounts[j] > 0: j += 1 ans.append(j) j += 1 return b" ".join(str(x).encode("ascii") for x in ans) if False: N, M = 10 ** 6, 10 ** 6 queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)] ans = solve(N, M, queries) # print(ans) assert ans != b"-1" exit() if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, M = [int(x) for x in input().split()] queries = ((int(x) for x in input().split()) for i in range(M)) ans = solve(N, M, queries) os.write(1, ans) ```
output
1
36,457
19
72,915
Provide tags and a correct Python 3 solution for this coding contest problem. The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: * each cup contains a mark β€” a number from 1 to n; all marks on the cups are distinct; * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input The first line contains integers n and m (1 ≀ n, m ≀ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≀ xi, yi ≀ n) β€” the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i. If there are multiple correct answers, you should print the lexicographically minimum one. Examples Input 2 1 2 1 Output 2 1 Input 3 2 1 2 1 1 Output 2 1 3 Input 3 3 1 3 2 3 1 3 Output -1
instruction
0
36,458
19
72,916
Tags: data structures Correct Solution: ``` import io import os # List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py class UnsortedList: def __init__(self, iterable=[], _load=400): """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] pass else: del _lists[pos] del _list_lens[pos] # del _mins[pos] self._rebuild = True 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 __setitem__(self, index, value): pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._lists[pos][idx] = value def insert(self, index, value): _load = self._load _lists = self._lists _list_lens = self._list_lens if _lists: pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _list_lens.append(1) self._rebuild = True self._len += 1 def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return "SortedList({0})".format(list(self)) def solve(N, M, queries): idToMark = [-1 for i in range(N)] cups = UnsortedList([i for i in range(N)]) for mark, pos in queries: pos -= 1 # 0-indexed cupId = cups[pos] del cups[pos] cups.insert(0, cupId) if idToMark[cupId] == -1: idToMark[cupId] = mark elif idToMark[cupId] != mark: return b"-1" markToCounts = [0 for i in range(N + 1)] for cupId, mark in enumerate(idToMark): if mark != -1: markToCounts[mark] += 1 if markToCounts[mark] > 1: return b"-1" j = 1 ans = [] for cupId, mark in enumerate(idToMark): if mark != -1: ans.append(mark) else: while markToCounts[j] > 0: j += 1 ans.append(j) j += 1 return b" ".join(str(x).encode("ascii") for x in ans) if False: N, M = 10 ** 6, 10 ** 6 queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)] ans = solve(N, M, queries) # print(ans) assert ans != b"-1" exit() if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, M = [int(x) for x in input().split()] queries = ((int(x) for x in input().split()) for i in range(M)) ans = solve(N, M, queries) os.write(1, ans) ```
output
1
36,458
19
72,917
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: * each cup contains a mark β€” a number from 1 to n; all marks on the cups are distinct; * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input The first line contains integers n and m (1 ≀ n, m ≀ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≀ xi, yi ≀ n) β€” the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i. If there are multiple correct answers, you should print the lexicographically minimum one. Examples Input 2 1 2 1 Output 2 1 Input 3 2 1 2 1 1 Output 2 1 3 Input 3 3 1 3 2 3 1 3 Output -1 Submitted Solution: ``` import io import os # List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py class UnsortedList: def __init__(self, iterable=[], _load=1000): """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] pass else: del _lists[pos] del _list_lens[pos] # del _mins[pos] self._rebuild = True 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 __setitem__(self, index, value): pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._lists[pos][idx] = value def insert(self, index, value): _load = self._load _lists = self._lists _list_lens = self._list_lens if _lists: pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _list_lens.append(1) self._rebuild = True self._len += 1 def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return "SortedList({0})".format(list(self)) def solve(N, M, queries): idToMark = [-1 for i in range(N)] cups = UnsortedList([i for i in range(N)]) for mark, pos in queries: pos -= 1 # 0-indexed cupId = cups[pos] del cups[pos] cups.insert(0, cupId) if idToMark[cupId] == -1: idToMark[cupId] = mark elif idToMark[cupId] != mark: return b"-1" markToCounts = [0 for i in range(N + 1)] for cupId, mark in enumerate(idToMark): if mark != -1: markToCounts[mark] += 1 if markToCounts[mark] > 1: return b"-1" j = 1 ans = [] for cupId, mark in enumerate(idToMark): if mark != -1: ans.append(mark) else: while markToCounts[j] > 0: j += 1 ans.append(j) j += 1 return b" ".join(str(x).encode("ascii") for x in ans) if True: N, M = 10 ** 6, 10 ** 6 queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)] ans = solve(N, M, queries) # print(ans) assert ans != b"-1" exit() if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, M = [int(x) for x in input().split()] queries = ((int(x) for x in input().split()) for i in range(M)) ans = solve(N, M, queries) os.write(1, ans) ```
instruction
0
36,459
19
72,918
No
output
1
36,459
19
72,919
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: * each cup contains a mark β€” a number from 1 to n; all marks on the cups are distinct; * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input The first line contains integers n and m (1 ≀ n, m ≀ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≀ xi, yi ≀ n) β€” the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i. If there are multiple correct answers, you should print the lexicographically minimum one. Examples Input 2 1 2 1 Output 2 1 Input 3 2 1 2 1 1 Output 2 1 3 Input 3 3 1 3 2 3 1 3 Output -1 Submitted Solution: ``` n,m=map(int,input().split()) L=[] Ans=[-1]*n E={} Q=[] valid=True Taken=[False]*n Pos=[0]*n for i in range(m): x,y=map(int,input().split()) x-=1 y-=1 a=-1 b=len(L) if(Ans[x]!=-1): if(y>=len(Q) or Q[y]!=x): print(-1) valid=False break else: Q.remove(x) Q=[x]+Q continue while(b-a>1): e=(b+a)//2 if(L[e]>=y): b=e else: a=e z=len(L)-b y-=z if(y<0): print(-1) valid=False break if(y in E): break E[y]=1 Ans[x]=y Taken[y]=True L.insert(a+1,y) Q=[x]+Q if(valid): ind=0 for i in range(n): if(Ans[i]==-1): while(Taken[ind]): ind+=1 Ans[i]=ind ind+=1 Pos[Ans[i]]=i for i in range(n): print(Pos[i]+1,end=" ") ```
instruction
0
36,460
19
72,920
No
output
1
36,460
19
72,921
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: * each cup contains a mark β€” a number from 1 to n; all marks on the cups are distinct; * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input The first line contains integers n and m (1 ≀ n, m ≀ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≀ xi, yi ≀ n) β€” the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i. If there are multiple correct answers, you should print the lexicographically minimum one. Examples Input 2 1 2 1 Output 2 1 Input 3 2 1 2 1 1 Output 2 1 3 Input 3 3 1 3 2 3 1 3 Output -1 Submitted Solution: ``` __author__ = 'Lipen' def main(): n, m = map(int, input().split()) data = [0]*n offset = 0 for i in range(m): x, y = map(int, input().split()) if x in data and data.index(x)!=y-1 + offset: #??? print(-1) return if x not in data: data[y-1 + offset] = x if y!=1: offset += 1 k = data.count(0) if k>0: j = 0 for i in range(1, n+1): if i not in data: data[data.index(0)] = i j+=1 if j>k: break print(' '.join(str(item) for item in data)) try: main() except: print(-1) ```
instruction
0
36,461
19
72,922
No
output
1
36,461
19
72,923
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: * each cup contains a mark β€” a number from 1 to n; all marks on the cups are distinct; * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input The first line contains integers n and m (1 ≀ n, m ≀ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≀ xi, yi ≀ n) β€” the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i. If there are multiple correct answers, you should print the lexicographically minimum one. Examples Input 2 1 2 1 Output 2 1 Input 3 2 1 2 1 1 Output 2 1 3 Input 3 3 1 3 2 3 1 3 Output -1 Submitted Solution: ``` import io import os import random # Based on https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/Treap.py WITH_QUERY = False if WITH_QUERY: default = float("inf") def mapVal(x): return x def combine(x, y): return min(x, y) class TreapList(object): root = 0 size = 0 def __init__(self, data=None): if data: self.root = treap_builder(data) self.size = len(data) def insert(self, index, value): self.root = treap_insert(self.root, index, value) self.size += 1 def __delitem__(self, index): self.root = treap_erase(self.root, index) self.size -= 1 def __setitem__(self, index, value): self.__delitem__(index) self.insert(index, value) def __getitem__(self, index): return treap_find_kth(self.root, index) def query(self, start, end): assert WITH_QUERY return treap_query(self.root, start, end) def bisect_left(self, value): return treap_bisect_left(self.root, value) # list must be sorted def bisect_right(self, value): return treap_bisect_right(self.root, value) # list must be sorted def __len__(self): return self.size def __nonzero__(self): return bool(self.root) __bool__ = __nonzero__ def __repr__(self): return "TreapMultiSet({})".format(list(self)) def __iter__(self): if not self.root: return iter([]) out = [] stack = [self.root] while stack: node = stack.pop() if node > 0: if right_child[node]: stack.append(right_child[node]) stack.append(~node) if left_child[node]: stack.append(left_child[node]) else: out.append(treap_keys[~node]) return iter(out) left_child = [0] right_child = [0] subtree_size = [0] if WITH_QUERY: subtree_query = [default] treap_keys = [0] treap_prior = [0.0] def treap_builder(data): """Build a treap in O(n) time""" def build(begin, end): if begin == end: return 0 mid = (begin + end) // 2 root = treap_create_node(data[mid]) lc = build(begin, mid) rc = build(mid + 1, end) left_child[root] = lc right_child[root] = rc subtree_size[root] = subtree_size[lc] + 1 + subtree_size[rc] if WITH_QUERY: subtree_query[root] = combine( combine(subtree_query[lc], mapVal(treap_keys[mid])), subtree_query[rc] ) # sift down the priorities ind = root while True: lc = left_child[ind] rc = right_child[ind] if lc and treap_prior[lc] > treap_prior[ind]: if rc and treap_prior[rc] > treap_prior[rc]: treap_prior[ind], treap_prior[rc] = ( treap_prior[rc], treap_prior[ind], ) ind = rc else: treap_prior[ind], treap_prior[lc] = ( treap_prior[lc], treap_prior[ind], ) ind = lc elif rc and treap_prior[rc] > treap_prior[ind]: treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind] ind = rc else: break return root return build(0, len(data)) def treap_create_node(key): treap_keys.append(key) treap_prior.append(random.random()) left_child.append(0) right_child.append(0) subtree_size.append(1) if WITH_QUERY: subtree_query.append(mapVal(key)) return len(treap_keys) - 1 def treap_split(root, index): if index == 0: return 0, root if index == subtree_size[root]: return root, 0 left_pos = right_pos = 0 stack = [] while root: left_size = subtree_size[left_child[root]] if left_size >= index: left_child[right_pos] = right_pos = root root = left_child[root] stack.append(right_pos) else: right_child[left_pos] = left_pos = root root = right_child[root] stack.append(left_pos) index -= left_size + 1 left, right = right_child[0], left_child[0] right_child[left_pos] = left_child[right_pos] = right_child[0] = left_child[0] = 0 treap_update(stack) check_invariant(left) check_invariant(right) return left, right def treap_merge(left, right): where, pos = left_child, 0 stack = [] while left and right: if treap_prior[left] > treap_prior[right]: where[pos] = pos = left where = right_child left = right_child[left] else: where[pos] = pos = right where = left_child right = left_child[right] stack.append(pos) where[pos] = left or right node = left_child[0] left_child[0] = 0 treap_update(stack) check_invariant(node) return node def treap_insert(root, index, value): if not root: return treap_create_node(value) left, right = treap_split(root, index) return treap_merge(treap_merge(left, treap_create_node(value)), right) def treap_erase(root, index): if not root: raise KeyError(index) if subtree_size[left_child[root]] == index: return treap_merge(left_child[root], right_child[root]) node = root stack = [root] while root: left_size = subtree_size[left_child[root]] if left_size > index: parent = root root = left_child[root] elif left_size == index: break else: parent = root root = right_child[root] index -= left_size + 1 stack.append(root) if not root: raise KeyError(index) if root == left_child[parent]: left_child[parent] = treap_merge(left_child[root], right_child[root]) else: right_child[parent] = treap_merge(left_child[root], right_child[root]) treap_update(stack) check_invariant(node) return node def treap_first(root): if not root: raise ValueError("min on empty treap") while left_child[root]: root = left_child[root] return root def treap_last(root): if not root: raise ValueError("max on empty treap") while right_child[root]: root = right_child[root] return root def treap_update(path): for node in reversed(path): assert node != 0 # ensure subtree_size[nullptr] == 0 lc = left_child[node] rc = right_child[node] subtree_size[node] = subtree_size[lc] + 1 + subtree_size[rc] if WITH_QUERY: subtree_query[node] = combine( combine(subtree_query[lc], mapVal(treap_keys[node])), subtree_query[rc] ) def check_invariant(node): return if node == 0: assert subtree_size[0] == 0 return 0 lc = left_child[node] rc = right_child[node] assert subtree_size[node] == subtree_size[lc] + 1 + subtree_size[rc] assert subtree_query[node] == combine( combine(subtree_query[lc], mapVal(treap_keys[node])), subtree_query[rc] ) check_invariant(lc) check_invariant(rc) def treap_find_kth(root, k): if not root or not (0 <= k < subtree_size[root]): raise IndexError("treap index out of range") while True: lc = left_child[root] left_size = subtree_size[lc] if k < left_size: root = lc continue k -= left_size if k == 0: return treap_keys[root] k -= 1 rc = right_child[root] # assert k < subtree_size[rc] root = rc def treap_bisect_left(root, key): index = 0 while root: if treap_keys[root] < key: index += subtree_size[left_child[root]] + 1 root = right_child[root] else: root = left_child[root] return index def treap_bisect_right(root, key): index = 0 while root: if treap_keys[root] <= key: index += subtree_size[left_child[root]] + 1 root = right_child[root] else: root = left_child[root] return index def treap_query(root, start, end): if not root or start == end: return default assert start < end if start == 0 and end == subtree_size[root]: return subtree_query[root] res = default # Find branching point right_node = right_start = left_node = left_start = -1 node = root node_start = 0 while node: # Current node's (left, key, mid) covers: # [node_start, node_start + left_size) # [node_start + left_size, node_start + left_size + 1) # [node_start + left_size + 1, node_start + left_size + 1 + right_size) lc = left_child[node] rc = right_child[node] left_size = subtree_size[lc] right_size = subtree_size[rc] node_end = node_start + subtree_size[node] assert node_start <= start < end <= node_end if end <= node_start + left_size: # [start, end) is in entirely in left child node = lc continue if node_start + left_size + 1 <= start: # [start, end) is in entirely in right child node_start += left_size + 1 node = rc continue # [start, end) covers some suffix of left, entire mid, and some prefix of right left_node = lc left_start = node_start res = combine(res, mapVal(treap_keys[node])) right_node = rc right_start = node_start + left_size + 1 break # Go down right node = right_node node_start = right_start node_end = right_start + subtree_size[node] if node_start < end: while node: lc = left_child[node] rc = right_child[node] left_size = subtree_size[lc] right_size = subtree_size[rc] node_end = node_start + subtree_size[node] assert start <= node_start < end <= node_end if node_start + left_size <= end: res = combine(res, subtree_query[lc]) node_start += left_size else: node = lc continue if node_start + 1 <= end: res = combine(res, mapVal(treap_keys[node])) node_start += 1 if node_start + right_size == end: res = combine(res, subtree_query[rc]) node_start += right_size if node_start == end: break node = rc # Go down left node = left_node node_start = left_start node_end = node_start + subtree_size[node] if start < node_end: while node: lc = left_child[node] rc = right_child[node] left_size = subtree_size[lc] right_size = subtree_size[rc] node_start = node_end - subtree_size[node] assert node_start <= start < node_end <= end if start <= node_end - right_size: res = combine(subtree_query[rc], res) node_end -= right_size else: node = rc continue if start <= node_end - 1: res = combine(mapVal(treap_keys[node]), res) node_end -= 1 if start <= node_end - left_size: res = combine(subtree_query[lc], res) node_end -= left_size if start == node_end: break node = lc return res # End treap copy and paste def solve(N, M, queries): mark = {} unusedMarks = set(range(1, N + 1)) cups = TreapList([i for i in range(N)]) for x, y in queries: y -= 1 cupId = cups[y] if cupId not in mark: if x not in unusedMarks: return -1 mark[cupId] = x unusedMarks.remove(x) else: if mark[cupId] != x: return -1 del cups[y] cups.insert(0, cupId) ans = [] for i in range(N): if i in mark: ans.append(mark[i]) else: ans.append(unusedMarks.pop()) return " ".join(map(str, ans)) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, M = [int(x) for x in input().split()] queries = [[int(x) for x in input().split()] for i in range(M)] ans = solve(N, M, queries) print(ans) ```
instruction
0
36,462
19
72,924
No
output
1
36,462
19
72,925
Provide tags and a correct Python 3 solution for this coding contest problem. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum.
instruction
0
36,531
19
73,062
Tags: binary search, brute force, dp, greedy, sortings, two pointers Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) 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 # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: 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: max(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) # -------------------------------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 binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y 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 (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,A,cf,cm,m=map(int,input().split()) l=list(map(int,input().split())) index=[i for i in range(n)] index=sort_list(index,l) l.sort() pre=[0]*(n+1) for i in range(1,n+1): pre[i]=pre[i-1]+l[i-1] def find(le,left,x): ind=binarySearchCount(l,le,x) if ind*x-(pre[ind]-pre[0])<=left: return True return False req=0 st=0 end=A sm=0 while(st<=end): mid=(st+end)//2 if find(n,m,mid)==True: sm=mid st=mid+1 else: end=mid-1 ans=sm*cm ind=n smf=sm for i in range(n-1,-1,-1): req+=A-l[i] left=m-req if left<0: break st=0 end=A sm=0 while(st<=end): mid=(st+end)//2 if find(i,left,mid)==True: sm=mid st=mid+1 else: end=mid-1 cur=(n-i)*cf+sm*cm if cur>ans: smf=sm ind=i ans=max(ans,cur) for i in range(n-1,ind-1,-1): l[i]=A for i in range(ind-1,-1,-1): if l[i]<smf: l[i]=smf l=sort_list(l,index) print(ans) print(*l) ```
output
1
36,531
19
73,063
Provide tags and a correct Python 3 solution for this coding contest problem. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum.
instruction
0
36,532
19
73,064
Tags: binary search, brute force, dp, greedy, sortings, two pointers Correct Solution: ``` n,A,cf,cm,mN = map(int,input().split()) a = list(map(int,input().split())) aCOPY = [] for elem in a: aCOPY.append(elem) a.sort() aPartialSum = [0] for elem in a: aPartialSum.append(aPartialSum[-1] + elem) maxScore = 0 ansMAXIBound = 0 ansMAXI = 0 ansMIN = 0 for MAXI in range(n + 1): currentScore = cf * MAXI if MAXI >= 1: mN -= (A - a[-MAXI]) if mN < 0: break if MAXI == n: maxScore = currentScore + A * cm ansMAXIBound = 0 ansMAXI = 10 ** 10 ansMIN = 0 # Find the maximum of minimum l = a[0] r = A - 1 while l < r: m = (l + r + 1) // 2 lA = 0 rA = n - MAXI - 1 while lA < rA: mA = (lA + rA) // 2 if a[mA] > m: rA = mA - 1 if a[mA] < m: lA = mA + 1 if a[mA] == m: lA = mA rA = mA break lA = min(lA,n - MAXI - 1) if a[lA] > m: lA -= 1 expenditure = (lA + 1) * m - aPartialSum[lA + 1] if expenditure > mN: r = m - 1 else: l = m currentScore += l * cm if currentScore > maxScore: maxScore = currentScore ansMAXIBound = a[-MAXI] ansMAXI = MAXI ansMIN = l print(maxScore) inclCount = 0 for i in range(n): if aCOPY[i] > ansMAXIBound and inclCount < ansMAXI: aCOPY[i] = A inclCount += 1 for i in range(n): if aCOPY[i] == ansMAXIBound and inclCount < ansMAXI: aCOPY[i] = A inclCount += 1 if aCOPY[i] < ansMIN: aCOPY[i] = ansMIN print(" ".join(map(str,aCOPY))) ```
output
1
36,532
19
73,065
Provide tags and a correct Python 3 solution for this coding contest problem. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum.
instruction
0
36,533
19
73,066
Tags: binary search, brute force, dp, greedy, sortings, two pointers Correct Solution: ``` f = lambda: map(int, input().split()) g = lambda: m - l * p[l - 1] + s[l] n, A, x, y, m = f() t = sorted((q, i) for i, q in enumerate(f())) p = [q for q, i in t] s = [0] * (n + 1) for j in range(n): s[j + 1] = p[j] + s[j] l = r = n F = L = R = B = -1 while 1: if p: while l > r or g() < 0: l -= 1 b = min(p[l - 1] + g() // l, A) else: b, l = A, 0 f = x * (n - r) + y * b if F < f: F, L, R, B = f, l, r, b if not p: break m += p.pop() - A r -= 1 if m < 0: break print(F) p = [(i, B if j < L else q if j < R else A) for j, (q, i) in enumerate(t)] for i, q in sorted(p): print(q) ```
output
1
36,533
19
73,067
Provide tags and a correct Python 3 solution for this coding contest problem. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum.
instruction
0
36,534
19
73,068
Tags: binary search, brute force, dp, greedy, sortings, two pointers Correct Solution: ``` def main(): from bisect import bisect n, A, cf, cm, m = map(int, input().split()) skills = list(map(int, input().split())) xlat = sorted(range(n), key=skills.__getitem__) sorted_skills = [skills[_] for _ in xlat] bottom_lift, a, c = [], 0, 0 for i, b in enumerate(sorted_skills): c += i * (b - a) bottom_lift.append(c) a = b root_lift, a = [0], 0 for b in reversed(sorted_skills): a += A - b root_lift.append(a) max_level = -1 for A_width, a in enumerate(root_lift): if m < a: break money_left = m - a floor_width = bisect(bottom_lift, money_left) if floor_width > n - A_width: floor_width = n - A_width money_left -= bottom_lift[floor_width - 1] if floor_width > 0: floor = sorted_skills[floor_width - 1] + money_left // floor_width if floor > A: floor = A else: floor = A level = cf * A_width + cm * floor if max_level < level: max_level, save = level, (A_width, floor, floor_width) A_width, floor, floor_width = save for id in xlat[:floor_width]: skills[id] = floor for id in xlat[n - A_width:]: skills[id] = A print(max_level) print(' '.join(map(str, skills))) if __name__ == '__main__': main() # Made By Mostafa_Khaled ```
output
1
36,534
19
73,069
Provide tags and a correct Python 3 solution for this coding contest problem. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum.
instruction
0
36,535
19
73,070
Tags: binary search, brute force, dp, greedy, sortings, two pointers Correct Solution: ``` import itertools import bisect n, A, cf, cm, m = [int(x) for x in input().split()] skills = [int(x) for x in input().split()] sorted_skills = list(sorted((k, i) for i, k in enumerate(skills))) bottom_lift = [0 for i in range(n)] for i in range(1, n): bottom_lift[i] = bottom_lift[i-1] + i * (sorted_skills[i][0] - sorted_skills[i-1][0]) root_lift = [0 for i in range(n+1)] for i in range(1, n+1): root_lift[i] = root_lift[i-1] + A - sorted_skills[n-i][0] max_level = -1 for i in range(n+1): money_left = m - root_lift[i] if money_left < 0: break k = min(bisect.bisect(bottom_lift, money_left), n-i) money_left -= bottom_lift[k-1] min_level = min(A, sorted_skills[k-1][0] + money_left//k) if k > 0 else A level = cf*i + cm*min_level if max_level < level: max_level = level argmax = i argmax_min_level = min_level argmax_k = k ans = [0 for i in range(n)] for i, skill in enumerate(sorted_skills): if i < argmax_k: ans[skill[1]] = argmax_min_level elif i >= n - argmax: ans[skill[1]] = A else: ans[skill[1]] = skill[0] print(max_level) for a in ans: print(a, end = ' ') ```
output
1
36,535
19
73,071
Provide tags and a correct Python 3 solution for this coding contest problem. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum.
instruction
0
36,536
19
73,072
Tags: binary search, brute force, dp, greedy, sortings, two pointers Correct Solution: ``` def main(): from bisect import bisect n, A, cf, cm, m = map(int, input().split()) skills = list(map(int, input().split())) xlat = sorted(range(n), key=skills.__getitem__) sorted_skills = [skills[_] for _ in xlat] bottom_lift, a, c = [], 0, 0 for i, b in enumerate(sorted_skills): c += i * (b - a) bottom_lift.append(c) a = b root_lift, a = [0], 0 for b in reversed(sorted_skills): a += A - b root_lift.append(a) max_level = -1 for A_width, a in enumerate(root_lift): if m < a: break money_left = m - a floor_width = bisect(bottom_lift, money_left) if floor_width > n - A_width: floor_width = n - A_width money_left -= bottom_lift[floor_width - 1] if floor_width > 0: floor = sorted_skills[floor_width - 1] + money_left // floor_width if floor > A: floor = A else: floor = A level = cf * A_width + cm * floor if max_level < level: max_level, save = level, (A_width, floor, floor_width) A_width, floor, floor_width = save for id in xlat[:floor_width]: skills[id] = floor for id in xlat[n - A_width:]: skills[id] = A print(max_level) print(' '.join(map(str, skills))) if __name__ == '__main__': main() ```
output
1
36,536
19
73,073
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum. Submitted Solution: ``` def main(): from bisect import bisect n, A, cf, cm, m = map(int, input().split()) skills = list(map(int, input().split())) idxes = sorted(range(n), key=skills.__getitem__) sorted_skills = [skills[_] for _ in idxes] bottom_lift, a = [0] * n, 0 for i, b in enumerate(sorted_skills): bottom_lift[i], a = (i * (b - a)), b root_lift, a = [0], 0 for b in reversed(sorted_skills): a += A - b root_lift.append(a) max_level = -1 for i, a in enumerate(root_lift): if m < a: break money_left = m - a k = min(bisect(bottom_lift, money_left), n - i) money_left -= bottom_lift[k - 1] min_level = sorted_skills[k - 1] + money_left // k if k > 0 else A if min_level > A: min_level = A level = cf * i + cm * min_level if max_level < level: max_level, sav = level, (i, min_level, k) i, min_level, k = sav for a, b in enumerate(idxes): if a < k: skills[b] = min_level elif a >= n - i: skills[b] = A print(max_level) print(' '.join(map(str, skills))) if __name__ == '__main__': main() ```
instruction
0
36,537
19
73,074
No
output
1
36,537
19
73,075
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum. Submitted Solution: ``` n,A,cf,cm,mN = map(int,input().split()) a = list(map(int,input().split())) aCOPY = [] for elem in a: aCOPY.append(elem) a.sort() aPartialSum = [0] for elem in a: aPartialSum.append(aPartialSum[-1] + elem) maxScore = 0 ansMAXIBound = 0 ansMAXI = 0 ansMIN = 0 for MAXI in range(n + 1): currentScore = cf * MAXI if MAXI >= 1: mN -= (A - a[-MAXI]) if mN < 0: break if MAXI == n: maxScore = currentScore ansMAXIBound = 0 ansMAXI = 10 ** 10 ansMIN = 10 ** 10 # Find the maximum of minimum l = a[0] r = A - 1 while l < r: m = (l + r + 1) // 2 lA = 0 rA = n - MAXI - 1 while lA < rA: mA = (lA + rA) // 2 if a[mA] > m: rA = mA - 1 if a[mA] < m: lA = mA + 1 if a[mA] == m: lA = mA rA = mA break lA = min(lA,n - MAXI - 1) if a[lA] > m: lA -= 1 expenditure = (lA + 1) * m - aPartialSum[lA + 1] if expenditure > mN: r = m - 1 else: l = m currentScore += l * cm if currentScore > maxScore: maxScore = currentScore ansMAXIBound = a[-MAXI] ansMAXI = MAXI ansMIN = l print(maxScore) inclCount = 0 for i in range(n): if aCOPY[i] > ansMAXIBound: aCOPY[i] = A inclCount += 1 for i in range(n): if aCOPY[i] == ansMAXIBound and inclCount < ansMAXI: aCOPY[i] = A inclCount += 1 if aCOPY[i] < ansMIN: aCOPY[i] = ansMIN print(" ".join(map(str,aCOPY))) ```
instruction
0
36,538
19
73,076
No
output
1
36,538
19
73,077
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum. Submitted Solution: ``` n,A,cf,cm,mN = map(int,input().split()) a = list(map(int,input().split())) aCOPY = [] for elem in a: aCOPY.append(elem) a.sort() aPartialSum = [0] for elem in a: aPartialSum.append(aPartialSum[-1] + elem) maxScore = 0 ansMAXIBound = 0 ansMAXI = 0 ansMIN = 0 for MAXI in range(n + 1): currentScore = cf * MAXI if MAXI >= 1: mN -= (A - a[-MAXI]) if mN < 0: break if MAXI == n: maxScore = currentScore ansMAXIBound = 0 ansMAXI = 10 ** 10 ansMIN = 10 ** 10 # Find the maximum of minimum l = a[0] r = A while l < r: m = (l + r + 1) // 2 lA = 0 rA = n - MAXI - 1 while lA < rA: mA = (lA + rA) // 2 if a[mA] > m: rA = mA - 1 if a[mA] < m: lA = mA + 1 if a[mA] == m: lA = mA rA = mA break lA = min(lA,n - MAXI - 1) if a[lA] > m: lA -= 1 expenditure = (lA + 1) * m - aPartialSum[lA + 1] if expenditure > mN: r = m - 1 else: l = m currentScore += l * cm if currentScore > maxScore: maxScore = currentScore ansMAXIBound = a[-MAXI] ansMAXI = MAXI ansMIN = l print(maxScore) inclCount = 0 for i in range(n): if aCOPY[i] > ansMAXIBound: aCOPY[i] = A inclCount += 1 for i in range(n): if aCOPY[i] == ansMAXIBound and inclCount < ansMAXI: aCOPY[i] = A inclCount += 1 if aCOPY[i] < ansMIN: aCOPY[i] = ansMIN print(" ".join(map(str,aCOPY))) ```
instruction
0
36,539
19
73,078
No
output
1
36,539
19
73,079
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β€” the current skill level. All skills have the same maximum level A. Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. * The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force. Input The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015). The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces, β€” the current levels of skills. Output On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces. Examples Input 3 5 10 1 5 1 3 1 Output 12 2 5 2 Input 3 5 10 1 339 1 3 1 Output 35 5 5 5 Note In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1. In the second test one should increase all skills to maximum. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) 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 # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: 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: max(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) # -------------------------------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 binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y 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 (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,A,cf,cm,m=map(int,input().split()) l=list(map(int,input().split())) index=[i for i in range(n)] index=sort_list(index,l) l.sort() pre=[0]*(n+1) for i in range(1,n+1): pre[i]=pre[i-1]+l[i-1] def find(le,left,x): ind=binarySearchCount(l,le,x) if ind*x-(pre[ind]-pre[0])<=left: return True return False req=0 st=0 end=A sm=0 while(st<=end): mid=(st+end)//2 if find(n,m,mid)==True: sm=mid st=mid+1 else: end=mid-1 ans=sm*cm ind=n smf=sm for i in range(n-1,-1,-1): req+=A-l[i] left=m-req if left<=0: break st=0 end=A sm=0 while(st<=end): mid=(st+end)//2 if find(n,left,mid)==True: sm=mid st=mid+1 else: end=mid-1 cur=(n-i)*cf+sm*cm if cur>ans: smf=sm ind=i ans=max(ans,cur) for i in range(n-1,ind-1,-1): l[i]=A for i in range(ind-1,-1,-1): l[i]=smf l=sort_list(l,index) print(ans) print(*l) ```
instruction
0
36,540
19
73,080
No
output
1
36,540
19
73,081
Provide tags and a correct Python 3 solution for this coding contest problem. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie.
instruction
0
36,606
19
73,212
Tags: dfs and similar, dp, games, graphs Correct Solution: ``` n, m = list(map(int, input().split())) from collections import defaultdict graph = defaultdict(list) for i in range(1, n + 1): neighbours = list(map(int, input().split()))[1:] graph[(i, 0)] = [(x, 1) for x in neighbours] graph[(i, 1)] = [(x, 0) for x in neighbours] start = int(input()) # terminal state terminal_states = [] for x in graph: if len(graph[x]) == 0 and x[1] == 1: terminal_states.append(x[0]) # Find if there is a path from (start,0) to (terminal,1) import sys stack = [(start, 0)] parents = {} visited = {} visited[(start, 0)] = True parents[(start, 0)] = None while (len(stack) != 0): current = stack.pop() for neighbour in graph[current]: if neighbour not in visited: stack.append(neighbour) visited[neighbour] = True parents[neighbour] = current for terminal in terminal_states: if (terminal, 1) in visited: print("Win") solution = [] current = (terminal, 1) while (current != None): solution.append(current[0]) current = parents[current] print(" ".join(list(map(str, solution[::-1])))) sys.exit() # Check for cycles in the graph from queue import Queue # we need an adjancy lsit of indegree .. actually only the value is enough ingoing_graph = defaultdict(int) for node in visited: ingoing_graph[node] += 0 for neighbour in graph[node]: if neighbour in visited: ingoing_graph[neighbour] += 1 zero_indegree_nodes = [] deleted = {} for node in ingoing_graph: if node in visited and ingoing_graph[node] == 0: zero_indegree_nodes.append(node) count = 0 while zero_indegree_nodes: current = zero_indegree_nodes.pop() count += 1 for neighbour in graph[current]: if neighbour not in deleted: ingoing_graph[neighbour] -= 1 if ingoing_graph[neighbour] == 0: zero_indegree_nodes.append(neighbour) deleted[neighbour] = True if count < len(visited): print("Draw") else: print("Lose") ```
output
1
36,606
19
73,213
Provide tags and a correct Python 3 solution for this coding contest problem. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie.
instruction
0
36,607
19
73,214
Tags: dfs and similar, dp, games, graphs Correct Solution: ``` import sys data = sys.stdin.readlines() n, m = map(int, data[0].split()) g = {} for i, line in enumerate(data[1:-1], 1): g[i] = list(map(int, line.split()[1:])) mk = {} start = int(data[-1]) queue = [(start, 0, -1, 1)] cycle = False while len(queue) > 0: v, player, prev, color = queue.pop() if color == 2: mk[(v, player)] = (prev, 2) continue if mk.get((v, player), None): if mk[(v, player)][1] == 1: cycle = True continue mk[(v, player)] = (prev, 1) queue.append((v, player, prev, 2)) for w in g[v]: queue.append((w, 1-player, v, 1)) sol = None for v in range(1, n+1): if len(g[v]) == 0 and mk.get((v, 1), None): sol = v break if sol: path = [sol] cur = (sol, 1) while cur != (start, 0): cur = (mk.get(cur)[0], 1-cur[1]) path.append(cur[0]) print('Win') print(*path[::-1]) elif cycle: print('Draw') else: print('Lose') ```
output
1
36,607
19
73,215
Provide tags and a correct Python 3 solution for this coding contest problem. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie.
instruction
0
36,608
19
73,216
Tags: dfs and similar, dp, games, graphs Correct Solution: ``` # -*- coding: utf-8 -*- n, m = [int(x) for x in input().split()] edges = [set()] drain = set() for i in range(n): nums = [int(x) for x in input().split()] if nums[0] == 0: drain.add(i + 1) edges.append(set(nums[1:])) start = int(input()) nodes = {start} visited = {} while len(nodes) > 0: curr = nodes.pop() for v in edges[abs(curr)]: if curr > 0: v = -v if visited.get(v) is None: nodes.add(v) visited[v] = curr ok = False for d in drain: if -d in visited: print('Win') v = -d l = [] while v != start: l.append(abs(v)) v = visited[v] l.append(start) print(' '.join(str(x) for x in l[::-1])) ok = True break if not ok: stack = [start] in_stack = {start} visited = {start} while len(stack) > 0: curr = stack[-1] if len(edges[curr]) == 0: stack.pop() in_stack.remove(curr) continue v = edges[curr].pop() if v not in visited: visited.add(v) stack.append(v) in_stack.add(v) elif v in in_stack: print('Draw') ok = True break if not ok: print('Lose') ```
output
1
36,608
19
73,217
Provide tags and a correct Python 3 solution for this coding contest problem. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie.
instruction
0
36,609
19
73,218
Tags: dfs and similar, dp, games, graphs Correct Solution: ``` n, m = [int(x) for x in input().split()] edges = [set()] drain = set() for i in range(n): nums = [int(x) for x in input().split()] if nums[0] == 0: drain.add(i + 1) edges.append(set(nums[1:])) start = int(input()) nodes = {start} visited = {} while len(nodes) > 0: curr = nodes.pop() for v in edges[abs(curr)]: if curr > 0: v = -v if visited.get(v) is None: nodes.add(v) visited[v] = curr ok = False for d in drain: if -d in visited: print('Win') v = -d l = [] while v != start: l.append(abs(v)) v = visited[v] l.append(start) print(' '.join(str(x) for x in l[::-1])) ok = True break if not ok: stack = [start] in_stack = {start} visited = {start} while len(stack) > 0: curr = stack[-1] if len(edges[curr]) == 0: stack.pop() in_stack.remove(curr) continue v = edges[curr].pop() if v not in visited: visited.add(v) stack.append(v) in_stack.add(v) elif v in in_stack: print('Draw') ok = True break if not ok: print('Lose') ```
output
1
36,609
19
73,219
Provide tags and a correct Python 3 solution for this coding contest problem. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie.
instruction
0
36,610
19
73,220
Tags: dfs and similar, dp, games, graphs Correct Solution: ``` n, m = [int(x) for x in input().split()] edges = [set()] drain = set() for i in range(n): nums = [int(x) for x in input().split()] if nums[0] == 0: drain.add(i + 1) edges.append(set(nums[1:])) start = int(input()) nodes = {start} visited = {} while len(nodes) > 0: curr = nodes.pop() for v in edges[abs(curr)]: if curr > 0: v = -v if visited.get(v) is None: nodes.add(v) visited[v] = curr ok = False for d in drain: if -d in visited: print('Win') v = -d l = [] while v != start: l.append(abs(v)) v = visited[v] l.append(start) print(' '.join(str(x) for x in l[::-1])) ok = True break if not ok: stack = [start] in_stack = {start} visited = {start} while len(stack) > 0: curr = stack[-1] if len(edges[curr]) == 0: stack.pop() in_stack.remove(curr) continue v = edges[curr].pop() if v not in visited: visited.add(v) stack.append(v) in_stack.add(v) elif v in in_stack: print('Draw') ok = True break if not ok: print('Lose') # Made By Mostafa_Khaled ```
output
1
36,610
19
73,221
Provide tags and a correct Python 3 solution for this coding contest problem. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie.
instruction
0
36,611
19
73,222
Tags: dfs and similar, dp, games, graphs Correct Solution: ``` # 936B import collections def do(): nodes, edges = map(int, input().split(" ")) outd = [0] * (nodes + 1) g = collections.defaultdict(list) for i in range(1, nodes + 1): tmp = [int(c) for c in input().split(" ")] outd[i] = tmp[0] g[i] = tmp[1:] dp = [[0] * 2 for _ in range(nodes + 1)] pre = [[0] * 2 for _ in range(nodes + 1)] st = int(input()) mask = [0] * (nodes + 1) def dfs(entry): has_loop = False stack = [[entry, 0, True]] dp[entry][0] = 1 # d[st][0], 0 means reach here by even(0) steps while stack: cur, step, first = stack.pop() if first: mask[cur] = 1 stack.append([cur, -1, False]) for nei in g[cur]: if mask[nei]: has_loop = True if dp[nei][step ^ 1]: continue pre[nei][step ^ 1] = cur dp[nei][step ^ 1] = 1 stack.append([nei, step ^ 1, first]) else: mask[cur] = 0 return has_loop has_loop = dfs(st) for i in range(1, nodes + 1): if outd[i] == 0: # out degree if dp[i][1]: # must reach here by odd steps print("Win") res = [] cur = i step = 1 while cur != st or step: res.append(cur) cur = pre[cur][step] step ^= 1 res.append(st) print(" ".join(str(c) for c in res[::-1])) return res = "Draw" if has_loop else "Lose" print(res) do() ```
output
1
36,611
19
73,223
Provide tags and a correct Python 3 solution for this coding contest problem. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie.
instruction
0
36,612
19
73,224
Tags: dfs and similar, dp, games, graphs Correct Solution: ``` n,m = map(int, input().split()) g = [[] for i in range(n)] fs = set() for i in range(n): a = list(map(int , input().split())) c = a[0] if c == 0: fs.add(i) continue for j in range(1,c+1): g[i].append(a[j]-1) s = int(input())-1 prev0 = [None for i in range(n)] prev1=[None for i in range(n)] vis0 = [0 for i in range(n)] vis0[s]=1 vis1 = [0 for i in range(n)] q = [(s, 0)] ans = None draw = False while len(q) > 0: v, c = q[0] del q[0] for u in g[v]: if c == 0: if vis1[u] == 0: vis1[u] =1 q.append((u, 1)) prev1[u] =v if u in fs: ans = u break elif c == 1: if vis0[u] == 0: vis0[u] =1 q.append((u, 0)) prev0[u] =v if ans is not None: break if ans is None: q = [s] vis=[0 for i in range(n)] vis[s]=1 nxt = [0 for i in range(n)] while len(q) > 0: v = q[-1] if nxt[v] < len(g[v]): u = g[v][nxt[v]] if vis[u] == 1: print('Draw') exit() elif vis[u] == 0: vis[u]=1 q.append(u) nxt[v] +=1 else: vis[v] = 2 del q[-1] print('Lose') exit() arn = [] nxt = ans while nxt is not None: arn.append(nxt) if len(arn) % 2 == 1: nxt = prev1[nxt] else: nxt = prev0[nxt] print('Win') arn = list(reversed(arn)) print(' '.join([str(i+1) for i in arn])) ```
output
1
36,612
19
73,225
Provide tags and a correct Python 3 solution for this coding contest problem. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie.
instruction
0
36,613
19
73,226
Tags: dfs and similar, dp, games, graphs Correct Solution: ``` # 936B import collections def do(): nodes, edges = map(int, input().split(" ")) outd = [0] * (nodes + 1) g = collections.defaultdict(set) for i in range(1, nodes + 1): tmp = [int(c) for c in input().split(" ")] outd[i] = tmp[0] g[i] = set(tmp[1:]) dp = [[0] * 2 for _ in range(nodes + 1)] pre = [[0] * 2 for _ in range(nodes + 1)] st = int(input()) mask = [0] * (nodes + 1) def dfs(entry): has_loop = False stack = [[entry, 0, True]] dp[entry][0] = 1 # d[st][0], 0 means reach here by even(0) steps while stack: cur, step, first = stack.pop() if first: mask[cur] = 1 stack.append([cur, -1, False]) for nei in g[cur]: if mask[nei] and outd[nei]: has_loop = True if dp[nei][step ^ 1]: continue pre[nei][step ^ 1] = cur dp[nei][step ^ 1] = 1 stack.append([nei, step ^ 1, first]) else: mask[cur] = 0 return has_loop has_loop = dfs(st) for i in range(1, nodes + 1): if outd[i] == 0: # out degree if dp[i][1]: # must reach here by odd steps print("Win") res = [] cur = i step = 1 while cur != st or step: res.append(cur) cur = pre[cur][step] step ^= 1 res.append(st) print(" ".join(str(c) for c in res[::-1])) return 0 if has_loop: print("Draw") else: print("Lose") return 0 do() ```
output
1
36,613
19
73,227
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie. Submitted Solution: ``` m,n = input().split(" ") for x in range(eval(m)): c = input() s = eval(input()) print("Lose") ```
instruction
0
36,614
19
73,228
No
output
1
36,614
19
73,229
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie. Submitted Solution: ``` import sys from collections import deque g = {} data = sys.stdin.readlines() n, m = map(int, data[0].split()) for i, line in enumerate(data[1:-1], 1): g[i] = list(map(int, line.split()[1:])) cycle = False mk = {} start = int(data[-1]) queue = deque() queue.append((start, 0, -1)) while len(queue) > 0: v, player, prev = queue.popleft() if mk.get((v, player), 0): cycle = True continue mk[(v, player)] = prev for w in g[v]: queue.append((w, 1-player, v)) sol = 0 for v in range(1, n+1): if len(g[v]) == 0 and mk.get((v, 1), 0): sol = v break if sol: path = [sol] cur = (sol, 1) while cur != (start, 0): cur = (mk.get(cur), 1-cur[1]) path.append(cur[0]) print('Win') print(*path[::-1]) elif cycle: print('Draw') else: print('Lose') ```
instruction
0
36,615
19
73,230
No
output
1
36,615
19
73,231
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie. Submitted Solution: ``` n, m = list(map(int, input().split())) from collections import defaultdict graph = defaultdict(list) for i in range(1, n + 1): neighbours = list(map(int, input().split()))[1:] graph[(i, 0)] = [(x, 1) for x in neighbours] graph[(i, 1)] = [(x, 0) for x in neighbours] start = int(input()) # terminal state terminal_states = [] for x in graph: if len(graph[x]) == 0: terminal_states.append(x[0]) # Find if there is a path from (start,0) to (terminal,1) import sys for terminal in terminal_states: stack = [(start, 0)] parents = {} visited = {} visited[(start, 0)] = True parents[(start, 0)] = None while (len(stack) != 0): current = stack.pop() if current == (terminal, 1): print("Win") solution = [] while (current != None): solution.append(current[0]) current = parents[current] print(" ".join(list(map(str,solution[::-1])))) sys.exit() for neighbour in graph[current]: if neighbour not in visited: stack.append(neighbour) visited[neighbour] = True parents[neighbour] = current # Check for cycles in the graph stack = [(start, 0)] inStack = {} visited = {} inStack[(start, 0)] = True visited[(start, 0)] = True while (len(stack) != 0): current = stack.pop() for neighbour in graph[current]: if neighbour in inStack: print("Draw") sys.exit() if neighbour not in visited: inStack[neighbour] = True stack.append(neighbour) visited[neighbour] = True del inStack[current] print("Lose") ```
instruction
0
36,616
19
73,232
No
output
1
36,616
19
73,233
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input The first line of input contain two integers n and m β€” the number of vertices and the number of edges in the graph (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105). The next n lines contain the information about edges of the graph. i-th line (1 ≀ i ≀ n) contains nonnegative integer ci β€” number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β€” indices of these vertices (1 ≀ ai, j ≀ n, ai, j β‰  i). It is guaranteed that the total sum of ci equals to m. The next line contains index of vertex s β€” the initial position of the chip (1 ≀ s ≀ n). Output If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≀ k ≀ 106) β€” the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Examples Input 5 6 2 2 3 2 4 5 1 4 1 5 0 1 Output Win 1 2 4 5 Input 3 2 1 3 1 1 0 2 Output Lose Input 2 2 1 2 1 1 1 Output Draw Note In the first example the graph is the following: <image> Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: <image> Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: <image> Petya can't win, but he can move along the cycle, so the players will draw a tie. Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 29 17:03:43 2020 @author: yuandali """ import sys sys.setrecursionlimit(10**5) #if cycle tie class SleepyGame: def noRecurse(self, start, G): path = [] visited = [False] * (n + 1) self.maxTurns = 10**6 stack = [(start, True)] visited[start] = True while stack: node, PetraTurn = stack.pop() if len(path) >= self.maxTurns: return 3 path.append(node) if not G[node]: if not PetraTurn: print('Win') print(*path, ' ') return else: path.pop() visited[node] = False continue for nextNode in G[node]: if visited[nextNode]: print('Draw') visited[nextNode] = True stack.append((nextNode, not PetraTurn)) print('Lose') import collections n, m = map(int, input().split()) G = collections.defaultdict(list) for i in range(1, n + 1): A = list(map(int, input().split())) G[i] += A[1:] start = int(input()) SleepyGame().noRecurse(start, G) ```
instruction
0
36,617
19
73,234
No
output
1
36,617
19
73,235
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8);
instruction
0
36,941
19
73,882
Tags: brute force, dp, greedy Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) me = a.index(-1) if me == n - 1: print(0) exit() for i in range(me + 1): a[i] = 0 dp = [[0] * n for _ in range(2)] opt = [[0] * n for _ in range(2)] dp[1][n - 1] = a[n - 1] if n - 1 <= me + 1: ans = a[n - 1] for i in range(2, 22): if 2 ** i > n: break s = i & 1 t = s ^ 1 l, r = n // 2 ** (i - 1) - 1, n - i + 1 pl, pr = n // 2 ** (i - 2) - 1, n - i + 2 opt[s][pr - 1] = dp[t][pr - 1] for j in range(pr - 2, pl - 1, -1): opt[s][j] = min(opt[s][j + 1], dp[t][j]) for j in range(pl - 1, l - 1, -1): opt[s][j] = opt[s][j + 1] for j in range(r - 1, l - 1, -1): dp[s][j] = opt[s][j + 1] + a[j] if l <= me + 1: ans = min(dp[s][l:r]) print(ans) ```
output
1
36,941
19
73,883
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8);
instruction
0
36,942
19
73,884
Tags: brute force, dp, greedy Correct Solution: ``` import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def main(): from itertools import accumulate n = int(input()) log = len(bin(n)) - 3 cnt = list(accumulate([0] + [n >> i for i in range(1, log + 1)])) + [0] a = list(map(int, input().split())) inf = 10**18 dp = [0] + [inf] * (log + 1) for i, v in zip(range(1, n + 1), reversed(a)): if v == -1: print(min(x for x in dp if x < inf)) exit() for j in range(log, -1, -1): if i <= cnt[j + 1]: dp[j + 1] = min(dp[j + 1], dp[j] + v) if i > cnt[j]: dp[j] = inf if __name__ == '__main__': main() ```
output
1
36,942
19
73,885
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8);
instruction
0
36,943
19
73,886
Tags: brute force, dp, greedy Correct Solution: ``` def main(): import sys from operator import itemgetter input = sys.stdin.readline N = int(input()) K = N.bit_length() - 1 A_raw = list(map(int, input().split())) flg = 1 A = [] for i, a in enumerate(A_raw): if flg: if a == -1: flg = 0 else: A.append(0) else: A.append(A_raw[i]) inf = 1<<40 dp = [[inf] * (K+1) for _ in range(N)] dp[0][0] = 0 for i in range(N): for j in range(K+1): if dp[i][j] < inf: if j < K: dp[i+1][j+1] = min(dp[i+1][j+1], dp[i][j] + A[N-2-i]) if N - 2**(K-j) > i: dp[i+1][j] = min(dp[i+1][j], dp[i][j]) print(dp[-1][-1]) if __name__ == '__main__': main() ```
output
1
36,943
19
73,887
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8);
instruction
0
36,944
19
73,888
Tags: brute force, dp, greedy Correct Solution: ``` from heapq import heappush, heappop N = int(input()) A = [int(a) for a in input().split()] for i in range(N): if A[i] < 0: k = i break A = [0] + [0 if i < k else A[i] for i in range(N) if i != k] ans = A.pop() H = [] while N > 2: N //= 2 for i in range(N): heappush(H, A.pop()) ans += heappop(H) print(ans) ```
output
1
36,944
19
73,889
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8);
instruction
0
36,945
19
73,890
Tags: brute force, dp, greedy Correct Solution: ``` import math import sys from sys import stdin, stdout #sys.setrecursionlimit(300000) # print(sys.getrecursionlimit()) # dp O(NlogN) def getMinimunCost(a, sum, i, j, dp): if dp[i][j] != -1: return dp[i][j] if a[j] == -1: return 0 remaining = sum[i] - j res = -2 if i < len(dp)-1: min1 = getMinimunCost(a, sum, i+1, j+1, dp) if min1 != -2: res = min1 + a[j] if remaining > 0: min2 = getMinimunCost(a, sum, i, j+1, dp) if res == -2: res = min2 elif min2 != -2: res = min(res, min2) dp[i][j] = res return dp[i][j] def getMinimunCost2(a, sum, dp): if a[0] == -1: for j in range(0, len(dp[0])): dp[0][j] = 0 else: for j in range(0, len(dp[0])): dp[0][j] = a[0] for i in range(1, len(dp)): for j in range(1, len(dp[i])): if j <= sum[i]: if j > 0: dp[i][j] = min(dp[i][j], dp[i][j-1]) if i > 0: dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + a[j]) else: dp[i][j] = min(dp[i][j], dp[i][j-1]) #break; #for i in range(len(dp)): # print(dp[i]) #print(a) return dp[-1][-1] if __name__ == '__main__': try: n = int(stdin.readline()) a = [int(i) for i in stdin.readline().split()] bcnt = int(math.log(n, 2)) sum = [] sum.append(0) x = int(n/2) for i in range(1, bcnt+1): sum.append(sum[i-1] + x) x = int(x/2) #dp = [[-1 for i in range(n)] for i in range(bcnt + 1)] dp = [[float("inf") for i in range(n)] for i in range(bcnt + 1)] #print(sum) #print(str(dp[0][0] + 1)) #set 0 flag = True for i in range(len(a)): if a[i] == -1: flag = False a[i] = 0 if flag: a[i] = 0 a.reverse() #res = getMinimunCost(a, sum, 0, 0, dp) res = getMinimunCost2(a, sum, dp) stdout.write(str(res)) except BaseException as e: print(str(e)) ```
output
1
36,945
19
73,891
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8);
instruction
0
36,946
19
73,892
Tags: brute force, dp, greedy Correct Solution: ``` import sys input = sys.stdin.readline import heapq as hq n = int(input()) a = list(map(int,input().split())) frn = a.index(-1)+1 t = n.bit_length() if frn == n: print(0) exit() ans = a[n-1] x = (frn-1).bit_length() q = [] hq.heapify(q) for i in range(1,t)[::-1]: for j in range(2**(i-1)-1,2**i-1): hq.heappush(q,a[j]) y = hq.heappop(q) if y >= 0: ans += y else: break print(ans) ```
output
1
36,946
19
73,893
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8);
instruction
0
36,947
19
73,894
Tags: brute force, dp, greedy Correct Solution: ``` from heapq import * n = int(input()) a = list(map(int, input().split())) done = a.index(-1) heap = [] cost = 0 x = n//2 position = n-1 while position > done: highest = a[position] he = min(heap) if heap else 10**10 if highest < he: cost += highest for val in a[position-1:position-x:-1]: heappush(heap, val) position -= x else: cost += he heappop(heap) for val in a[position:position-x:-1]: heappush(heap, val) position -= x x //= 2 print(cost) ```
output
1
36,947
19
73,895
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8);
instruction
0
36,948
19
73,896
Tags: brute force, dp, greedy Correct Solution: ``` import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def main(): from itertools import accumulate n = int(input()) log = len(bin(n)) - 3 cnt = list(accumulate([0] + [n >> i for i in range(1, log + 1)])) + [0] a = list(map(float, input().split())) inf = float('inf') dp = [0] + [inf] * (log + 1) for i, v in zip(range(1, n + 1), reversed(a)): if v == -1: print(int(min(x for x in dp if x < inf) + 1e-8)) exit() for j in range(log, -1, -1): if i <= cnt[j + 1]: dp[j + 1] = min(dp[j + 1], dp[j] + v) if i > cnt[j]: dp[j] = inf if __name__ == '__main__': main() ```
output
1
36,948
19
73,897
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8); Submitted Solution: ``` from math import log2, floor def is_power2(num): return num != 0 and ((num & (num - 1)) == 0) def next_two_pow(val): pw=0 while 2**pw <= val: pw=+1 return pw n = int(input()) arr=[int(x) for x in input().split()] win_idx =-1 selected=[] for i in range(1,n+1): val = arr[i-1] if win_idx ==-1: if val == -1: win_idx =i else: if is_power2(i): selected.append(val) selected.sort() else: if len(selected) > 0 and val < selected[-1]: selected.pop() selected.append(val) selected.sort() print(sum(selected)) # if arr[n-1] ==-1: # print(0) # else: # win_idx =-1 # for i in range(0,n): # if arr[i] == -1: # win_idx =i # break # # crt_pow=int(floor(log2(n))) # stop_pow=next_two_pow(win_idx) # total=0 # taken= set() # while crt_pow > stop_pow: # two_p = 2**crt_pow # mn = 10**9 + 1 # mn_idx = -1 # for i in range(two_p - 1, n): # if i!=win_idx and i not in taken and arr[i] < mn: # mn =arr[i] # mn_idx=i # crt_pow -=1 # taken.add(mn_idx) # total+=mn # print(total) ```
instruction
0
36,949
19
73,898
Yes
output
1
36,949
19
73,899
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8); Submitted Solution: ``` import sys from heapq import heappop, heappush from math import log2 # inf = open('input.txt', 'r') # reader = (map(int, line.split()) for line in inf) reader = (map(int, s.split()) for s in sys.stdin) def bribe(n, a): if a[-1] < 0: return 0 fr = a.index(-1) a[fr] = float('inf') h = int(log2(n)) k = int(log2(fr + 1)) total = a[-1] hq = [] for r in range(h - 1, k, -1): [heappush(hq, a[i]) for i in range(2 ** r - 1, 2 ** (r + 1) - 1)]; opponent = heappop(hq) total += opponent return total n, = next(reader) a = list(next(reader)) ans = bribe(n, a) print(ans) # inf.close() ```
instruction
0
36,950
19
73,900
Yes
output
1
36,950
19
73,901
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8); Submitted Solution: ``` import sys input = sys.stdin.readline n=int(input()) A=list(map(int,input().split())) x=A.index(-1) for i in range(x+1): A[i]=0 B=list(reversed(A)) import heapq H=[] ANS=0 LIST=[0]+[n-(1<<i)+1 for i in range(n.bit_length()-1,0,-1)] for i in range(1,n.bit_length()): for j in range(LIST[i-1],LIST[i]): heapq.heappush(H,B[j]) #print(H) x=heapq.heappop(H) ANS+=x print(ANS) ```
instruction
0
36,951
19
73,902
Yes
output
1
36,951
19
73,903
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8); Submitted Solution: ``` import heapq pop=heapq.heappop push=heapq.heappush n=int(input()) a=list(map(int, input().split())) ans=0 pos=-1 for i, x in enumerate(a): if x==-1: pos=i break if pos==n-1: print(0) else: ans += a[n-1] cur = n-2 used = [0] * n used[pos] = 1 used[n-1] = 1 Q=[] i=n//2 while i>=2: for _ in range(i): while used[cur]==1: cur-=1 val=0 if cur < pos else a[cur] push(Q, (val, cur)) cur-=1 while True: x, p = pop(Q) if used[p]==0: break used[p]=1 #print(p, a[p]) if p > pos: ans+=a[p] i//=2 print(ans) ```
instruction
0
36,952
19
73,904
Yes
output
1
36,952
19
73,905
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8); Submitted Solution: ``` import math import sys from sys import stdin, stdout #sys.setrecursionlimit(1500) # dp O(NlogN) def getMinimunCost(a, sum, i, j, dp): if dp[i][j] != -1: return dp[i][j] if a[j] == -1: return 0 remaining = sum[i] - j res = -2 if i < len(dp)-1: min1 = getMinimunCost(a, sum, i+1, j+1, dp) if min1 != -2: res = min1 + a[j] if remaining > 0: min2 = getMinimunCost(a, sum, i, j+1, dp) if res == -2: res = min2 elif min2 != -2: res = min(res, min2) dp[i][j] = res return dp[i][j] if __name__ == '__main__': try: n = int(stdin.readline()) a = [int(i) for i in stdin.readline().split()] bcnt = int(math.log(n, 2)) sum = [] sum.append(0) x = int(n/2) for i in range(1, bcnt+1): sum.append(sum[i-1] + x) x = int(x/2) dp = [[-1 for i in range(n)] for i in range(bcnt + 1)] #print(sum) #print(dp) a.reverse() res = getMinimunCost(a, sum, 0, 0, dp) stdout.write(str(res)) except BaseException as e: print(str(e)) ```
instruction
0
36,953
19
73,906
No
output
1
36,953
19
73,907
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8); Submitted Solution: ``` import math import sys from sys import stdin, stdout sys.setrecursionlimit(2000) # dp O(NlogN) def getMinimunCost(a, sum, i, j, dp): if dp[i][j] != -1: return dp[i][j] if a[j] == -1: return 0 remaining = sum[i] - j res = -2 if i < len(dp)-1: min1 = getMinimunCost(a, sum, i+1, j+1, dp) if min1 != -2: res = min1 + a[j] if remaining > 0: min2 = getMinimunCost(a, sum, i, j+1, dp) if res == -2: res = min2 elif min2 != -2: res = min(res, min2) dp[i][j] = res return dp[i][j] if __name__ == '__main__': try: n = int(stdin.readline()) a = [int(i) for i in stdin.readline().split()] bcnt = int(math.log(n, 2)) sum = [] sum.append(0) x = int(n/2) for i in range(1, bcnt+1): sum.append(sum[i-1] + x) x = int(x/2) dp = [[-1 for i in range(n)] for i in range(bcnt + 1)] #print(sum) #print(dp) a.reverse() res = getMinimunCost(a, sum, 0, 0, dp) stdout.write(str(res)) except BaseException as e: print(str(e)) ```
instruction
0
36,954
19
73,908
No
output
1
36,954
19
73,909
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8); Submitted Solution: ``` import math import sys from sys import stdin, stdout #sys.setrecursionlimit(300000) # print(sys.getrecursionlimit()) # dp O(NlogN) def getMinimunCost(a, sum, i, j, dp): if dp[i][j] != -1: return dp[i][j] if a[j] == -1: return 0 remaining = sum[i] - j res = -2 if i < len(dp)-1: min1 = getMinimunCost(a, sum, i+1, j+1, dp) if min1 != -2: res = min1 + a[j] if remaining > 0: min2 = getMinimunCost(a, sum, i, j+1, dp) if res == -2: res = min2 elif min2 != -2: res = min(res, min2) dp[i][j] = res return dp[i][j] def getMinimunCost2(a, sum, dp): if a[0] == -1: for j in range(0, len(dp[0])): dp[0][j] = 0 else: for j in range(0, len(dp[0])): dp[0][j] = a[0] for i in range(1, len(dp)): for j in range(1, len(dp[i])): if j <= sum[i]: if j > 0: dp[i][j] = min(dp[i][j], dp[i][j-1]) if i > 0: dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + a[j]) else: dp[i][j] = min(dp[i][j], dp[i][j-1]) #break; #for i in range(len(dp)): # print(dp[i]) #print(a) return dp[-1][-1] if __name__ == '__main__': try: n = int(stdin.readline()) a = [int(i) for i in stdin.readline().split()] bcnt = int(math.log(n, 2)) sum = [] sum.append(0) x = int(n/2) for i in range(1, bcnt+1): sum.append(sum[i-1] + x) x = int(x/2) #dp = [[-1 for i in range(n)] for i in range(bcnt + 1)] dp = [[sys.maxsize for i in range(n)] for i in range(bcnt + 1)] #print(sum) #print(dp) #set 0 flag = True for i in range(len(a)): if a[i] == -1: flag = False a[i] = 0 if flag: a[i] = 0 a.reverse() #res = getMinimunCost(a, sum, 0, 0, dp) res = getMinimunCost2(a, sum, dp) stdout.write(str(res)) except BaseException as e: print(str(e)) ```
instruction
0
36,955
19
73,910
No
output
1
36,955
19
73,911
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner). Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower. Furthermore, during each stage you distribute the boxers into pairs as you wish. The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish? Input The first line contains one integer n (2 ≀ n ≀ 2^{18}) β€” the number of boxers. n is a power of 2. The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β€” it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9]. Output Print one integer β€” the minimum number of dollars you have to pay so your friend wins. Examples Input 4 3 9 1 -1 Output 0 Input 8 11 -1 13 19 24 7 17 5 Output 12 Note In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament. In the second test case you can distribute boxers as follows (your friend is number 2): 1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage); 2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6); 2 : 8 (you have to bribe the boxer with strength 8); Submitted Solution: ``` n=int(input()) res=0 arr=[int(i) for i in input().split()] while n>2: if arr.index(-1) >= n - 1: res += 0 break else: res += sorted(arr)[1] arr.remove(sorted(arr)[1]) n/=2 if arr.index(-1) >= n - 1: res += 0 else: res += sorted(arr)[1] print(res) ```
instruction
0
36,956
19
73,912
No
output
1
36,956
19
73,913
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards. A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≀ i<n. To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck? Input The first line contains a single integer n (1≀ n≀ 2β‹… 10^5) β€” the number of cards. The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≀ a_i, b_i≀ 2n). Every integer between 1 and 2n appears exactly once. Output If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck. Examples Input 5 3 10 6 4 1 9 5 8 2 7 Output 2 Input 2 1 2 3 4 Output -1 Input 3 1 2 3 6 4 5 Output -1 Note In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1. In the second test case, it is impossible to sort the deck. Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n = int(input()) cards = [] cardsLocation = [0] * (2 * n) covered = [False] * (2 * n) for i in range(n): a,b = map(int,input().split()) cards.append((a-1, b-1)) cardsLocation[cards[i][0]] = i cardsLocation[cards[i][1]] = i upList = [] downList = [] curMin = -1 curMax = 2 * n curCoveredMin = -1 curCoveredMax = 2 * n cnt = 0 ans = 0 flag = True while True: if curCoveredMin == curCoveredMax - 1: break f = 0 b = 0 curMin += 1 curCoveredMin += 1 k = cardsLocation[curMin] if cards[k][0] == curMin: f += 1 curMax = cards[k][1] else: b += 1 curMax = cards[k][0] covered[cards[k][0]] = 1 covered[cards[k][1]] = 1 upList.append(k) cnt += 1 while curCoveredMax > curMax or curCoveredMin < curMin: while curCoveredMax > curMax: if covered[curCoveredMax - 1] == True: curCoveredMax -= 1 else: k = cardsLocation[curCoveredMax - 1] if cards[k][0] == curCoveredMax - 1: smallSide = cards[k][1] else: smallSide = cards[k][0] flag2 = False if not upList or (min(cards[upList[-1]]) < smallSide and max(cards[upList[-1]]) > curCoveredMax - 1): upList.append(k) if cards[k][0] == curCoveredMax - 1: b += 1 else: f += 1 flag2 = True elif not downList or (max(cards[downList[-1]]) > smallSide and min(cards[downList[-1]]) < curCoveredMax - 1): downList.append(k) if cards[k][0] == curCoveredMax - 1: f += 1 else: b += 1 flag2 = True if not flag2: flag = False break covered[smallSide] = 1 covered[curCoveredMax - 1] = 1 curMin = max(smallSide, curMin) curCoveredMax -= 1 if not flag: break while curCoveredMin < curMin: if covered[curCoveredMin + 1] == True: curCoveredMin += 1 else: k = cardsLocation[curCoveredMin + 1] if cards[k][0] == curCoveredMin + 1: bigSide = cards[k][1] else: bigSide = cards[k][0] flag2 = False if not upList or (min(cards[upList[-1]]) < curCoveredMin + 1 and max(cards[upList[-1]]) > bigSide): upList.append(k) if cards[k][0] == curCoveredMin + 1: f += 1 else: b += 1 flag2 = True elif not downList or (min(cards[downList[-1]]) > curCoveredMin + 1 and max(cards[downList[-1]]) < bigSide): downList.append(k) if cards[k][0] == curCoveredMin + 1: b += 1 else: f += 1 flag2 = True if not flag2: flag = False break covered[bigSide] = 1 covered[curCoveredMin + 1] = 1 curMax = min(bigSide, curMax) curCoveredMin += 1 if not flag: break if not flag: break if curMin >= curMax: flag = False break ans += min(b, f) print(ans if flag and (not upList or not downList or (min(cards[upList[-1]]) < max(cards[downList[-1]]) and min(cards[upList[-1]]) < max(cards[downList[-1]]))) else -1) # 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") # endregion if __name__ == "__main__": main() ```
instruction
0
37,059
19
74,118
No
output
1
37,059
19
74,119
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards. A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≀ i<n. To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck? Input The first line contains a single integer n (1≀ n≀ 2β‹… 10^5) β€” the number of cards. The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≀ a_i, b_i≀ 2n). Every integer between 1 and 2n appears exactly once. Output If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck. Examples Input 5 3 10 6 4 1 9 5 8 2 7 Output 2 Input 2 1 2 3 4 Output -1 Input 3 1 2 3 6 4 5 Output -1 Note In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1. In the second test case, it is impossible to sort the deck. Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n = int(input()) cards = [] cardsLocation = [0] * (2 * n) covered = [False] * (2 * n) for i in range(n): a,b = map(int,input().split()) cards.append((a-1, b-1)) cardsLocation[cards[i][0]] = i cardsLocation[cards[i][1]] = i upList = [] downList = [] curMin = -1 curMax = 2 * n curCoveredMin = -1 curCoveredMax = 2 * n cnt = 0 ans = 0 flag = True while True: if curCoveredMin == curCoveredMax - 1: break f = 0 b = 0 curMin += 1 curCoveredMin += 1 k = cardsLocation[curMin] if cards[k][0] == curMin: f += 1 curMax = cards[k][1] else: b += 1 curMax = cards[k][0] covered[cards[k][0]] = 1 covered[cards[k][1]] = 1 upList.append(k) cnt += 1 while curCoveredMax > curMax or curCoveredMin < curMin: while curCoveredMax > curMax: if covered[curCoveredMax - 1] == True: curCoveredMax -= 1 else: k = cardsLocation[curCoveredMax - 1] if cards[k][0] == curCoveredMax - 1: smallSide = cards[k][1] else: smallSide = cards[k][0] flag2 = False if not upList or (min(cards[upList[-1]]) < smallSide and max(cards[upList[-1]]) > curCoveredMax - 1): upList.append(k) if cards[k][0] == curCoveredMax - 1: b += 1 else: f += 1 flag2 = True elif not downList or (max(cards[downList[-1]]) > smallSide and min(cards[downList[-1]]) < curCoveredMax - 1): downList.append(k) if cards[k][0] == curCoveredMax - 1: f += 1 else: b += 1 flag2 = True if not flag2: flag = False break covered[smallSide] = 1 covered[curCoveredMax - 1] = 1 curMin = max(smallSide, curMin) curCoveredMax -= 1 if not flag: break while curCoveredMin < curMin: if covered[curCoveredMin + 1] == True: curCoveredMin += 1 else: k = cardsLocation[curCoveredMin + 1] if cards[k][0] == curCoveredMin + 1: bigSide = cards[k][1] else: bigSide = cards[k][0] flag2 = False if not upList or (min(cards[upList[-1]]) < curCoveredMin + 1 and max(cards[upList[-1]]) > bigSide): upList.append(k) if cards[k][0] == curCoveredMin + 1: f += 1 else: b += 1 flag2 = True elif not downList or (min(cards[downList[-1]]) > curCoveredMin + 1 and max(cards[downList[-1]]) < bigSide): downList.append(k) if cards[k][0] == curCoveredMin - 1: b += 1 else: f += 1 flag2 = True if not flag2: flag = False break covered[bigSide] = 1 covered[curCoveredMin + 1] = 1 curMax = min(bigSide, curMax) curCoveredMin += 1 if not flag: break if not flag: break if curMin >= curMax: flag = False break ans += min(b, f) print(ans if flag and (not upList or not downList or (min(cards[upList[-1]]) < max(cards[downList[-1]]) and max(cards[upList[-1]]) > max(cards[downList[-1]]))) else -1) # 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") # endregion if __name__ == "__main__": main() ```
instruction
0
37,060
19
74,120
No
output
1
37,060
19
74,121
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards. A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≀ i<n. To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck? Input The first line contains a single integer n (1≀ n≀ 2β‹… 10^5) β€” the number of cards. The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≀ a_i, b_i≀ 2n). Every integer between 1 and 2n appears exactly once. Output If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck. Examples Input 5 3 10 6 4 1 9 5 8 2 7 Output 2 Input 2 1 2 3 4 Output -1 Input 3 1 2 3 6 4 5 Output -1 Note In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1. In the second test case, it is impossible to sort the deck. Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n = int(input()) cards = [] cardsLocation = [0] * (2 * n) covered = [False] * (2 * n) for i in range(n): a,b = map(int,input().split()) cards.append((a-1, b-1)) cardsLocation[cards[i][0]] = i cardsLocation[cards[i][1]] = i upList = [] downList = [] curMin = -1 curMax = 2 * n curCoveredMin = -1 curCoveredMax = 2 * n cnt = 0 ans = 0 flag = True while True: if curCoveredMin == curCoveredMax - 1: break f = 0 b = 0 curMin += 1 curCoveredMin += 1 k = cardsLocation[curMin] if cards[k][0] == curMin: f += 1 curMax = cards[k][1] else: b += 1 curMax = cards[k][0] covered[cards[k][0]] = 1 covered[cards[k][1]] = 1 upList.append(k) cnt += 1 while curCoveredMax > curMax or curCoveredMin < curMin: while curCoveredMax > curMax: if covered[curCoveredMax - 1] == True: curCoveredMax -= 1 else: k = cardsLocation[curCoveredMax - 1] if cards[k][0] == curCoveredMax - 1: smallSide = cards[k][1] else: smallSide = cards[k][0] flag2 = False if not upList or (min(cards[upList[-1]]) < smallSide and max(cards[upList[-1]]) > curCoveredMax - 1): upList.append(k) if cards[k][0] == curCoveredMax - 1: b += 1 else: f += 1 flag2 = True elif not downList or (max(cards[downList[-1]]) > smallSide and min(cards[downList[-1]]) < curCoveredMax - 1): downList.append(k) if cards[k][0] == curCoveredMax - 1: f += 1 else: b += 1 flag2 = True if not flag2: flag = False break covered[smallSide] = 1 covered[curCoveredMax - 1] = 1 curMin = max(smallSide, curMin) curCoveredMax -= 1 if not flag: break while curCoveredMin < curMin: if covered[curCoveredMin + 1] == True: curCoveredMin += 1 else: k = cardsLocation[curCoveredMin + 1] if cards[k][0] == curCoveredMin + 1: bigSide = cards[k][1] else: bigSide = cards[k][0] flag2 = False if not upList or (min(cards[upList[-1]]) < curCoveredMin + 1 and max(cards[upList[-1]]) > bigSide): upList.append(k) if cards[k][0] == curCoveredMin + 1: f += 1 else: b += 1 flag2 = True elif not downList or (min(cards[downList[-1]]) > curCoveredMin + 1 and max(cards[downList[-1]]) < bigSide): downList.append(k) if cards[k][0] == curCoveredMin - 1: b += 1 else: f += 1 flag2 = True if not flag2: flag = False break covered[bigSide] = 1 covered[curCoveredMin + 1] = 1 curMax = min(bigSide, curMax) curCoveredMin += 1 if not flag: break if not flag: break if curMin >= curMax: flag = False break ans += min(b, f) print(ans if flag and (not upList or not downList or (min(cards[upList[-1]]) < max(cards[downList[-1]]) and min(cards[upList[-1]]) < max(cards[downList[-1]]))) else -1) # 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") # endregion if __name__ == "__main__": main() ```
instruction
0
37,062
19
74,124
No
output
1
37,062
19
74,125
Provide tags and a correct Python 3 solution for this coding contest problem. Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: * the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers <image> the condition |ci - cj| ≀ 1 must hold. * if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions. Input The first line contains single integer n (1 ≀ n ≀ 1000) β€” the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8 β€” the description of Vladik's sequence. Output Print single integer β€” the length of the longest subsequence of Vladik's sequence that satisfies both conditions. Examples Input 3 1 1 1 Output 1 Input 8 8 7 6 5 4 3 2 1 Output 8 Input 24 1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8 Output 17 Note In the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.
instruction
0
37,339
19
74,678
Tags: binary search, bitmasks, brute force, dp Correct Solution: ``` import copy def solve(): n = int(input()) a = [int(c)-1 for c in input().split(' ')] nextcard = [[-1 for i in range(8)] for j in range(n)] for i in range(n-2, -1, -1): nextcard[i] = copy.copy(nextcard[i+1]) nextcard[i][a[i+1]] = i+1 jump = [[-1 for i in range(n+1)] for j in range(n)] for i in range(n): card = a[i] cpos = i j = 1 while cpos != -1: jump[i][j] = cpos j+=1 cpos = nextcard[cpos][card] #Find dp solution for range (val, val+1) def getLen(val): dp = [[-1 for i in range(1<<8)] for j in range(n+1)] dp[0][0] = 0 for i in range(n): card = a[i] for comb in range(1<<8): if (comb & (1<<card)) == 0 and dp[i][comb] != -1: ncomb = comb + (1<<card) if jump[i][val] != -1: j = jump[i][val]+1 dp[j][ncomb] = max(dp[j][ncomb], dp[i][comb] + val) if jump[i][val+1] != -1: j = jump[i][val+1]+1 dp[j][ncomb] = max(dp[j][ncomb], dp[i][comb] + val + 1) dp[i+1][comb] = max(dp[i+1][comb], dp[i][comb]) return dp[n][(1<<8)-1] appear = [False for i in range(8)] for c in a: appear[c] = True result = 0 for c in appear: result += int(c) #Finally binary search to find the result cur = 0 for lev in range(9, -1, -1): tpow = (1<<lev) if cur + tpow < n: ret = getLen(cur + tpow) if(ret != -1): result = max(result, ret) cur += tpow return result print(solve()) ```
output
1
37,339
19
74,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: * the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers <image> the condition |ci - cj| ≀ 1 must hold. * if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions. Input The first line contains single integer n (1 ≀ n ≀ 1000) β€” the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8 β€” the description of Vladik's sequence. Output Print single integer β€” the length of the longest subsequence of Vladik's sequence that satisfies both conditions. Examples Input 3 1 1 1 Output 1 Input 8 8 7 6 5 4 3 2 1 Output 8 Input 24 1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8 Output 17 Note In the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition. Submitted Solution: ``` # coding=utf-8 __author__ = 'Alexander' n = int(input()) c = list(map(int,input().split())) t = [0] * 8 for x in c: t[x-1] += 1 m = min(t) f = 8*m for x in t: if x > m: f += 1 print(f) ```
instruction
0
37,340
19
74,680
No
output
1
37,340
19
74,681