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 a correct Python 3 solution for this coding contest problem.
Let's play the game using a bag containing several cards with integers written on it. In each game, participants first declare one of their favorite number n. Then, take out an appropriate number of cards from the bag at a time, and if the sum of the numbers written on those cards is equal to n, you will receive a luxurious prize. After each game, the cards will be returned to the bag.
Create a program that inputs the information of m types of cards in the bag and the number declared by the participants in g games, and outputs how many combinations of cards can receive luxury products in each game. please.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
m
a1 b1
a2 b2
::
am bm
g
n1
n2
::
ng
The number of card types m (1 β€ m β€ 7) on the first line, the integer ai (1 β€ ai β€ 100) written on the i-type card on the following m line, and the number bi (1 β€ bi β€ 10) Are given with a space delimiter.
The next line is given the number of games g (1 β€ g β€ 10), and the next g line is given the integer ni (1 β€ ni β€ 1,000) declared in game i.
The number of datasets does not exceed 100.
Output
For each input dataset, the i line prints the number of card combinations that will give you a gorgeous prize in Game i.
Example
Input
5
1 10
5 3
10 3
25 2
50 2
4
120
500
100
168
7
1 10
3 10
5 10
10 10
25 10
50 10
100 10
3
452
574
787
0
Output
16
0
12
7
9789
13658
17466 | instruction | 0 | 101,971 | 19 | 203,942 |
"Correct Solution:
```
def get_input():
while True:
try:
yield ''.join(input())
except EOFError:
break
while True:
m = int(input())
if m == 0:
break
a = [0 for i in range(7)]
b = [0 for i in range(7)]
for i in range(m):
a[i],b[i] = [int(j) for j in input().split()]
dp = [[0 for i in range(1001)] for j in range(8)]
dp[0][0] = 1
for i in range(7):
for j in range(1001):
for k in range(b[i] + 1):
if j + a[i]*k <= 1000:
dp[i+1][j + a[i]*k] += dp[i][j]
g = int(input())
for i in range(g):
n = int(input())
print(dp[m][n])
``` | output | 1 | 101,971 | 19 | 203,943 |
Provide a correct Python 3 solution for this coding contest problem.
Let's play the game using a bag containing several cards with integers written on it. In each game, participants first declare one of their favorite number n. Then, take out an appropriate number of cards from the bag at a time, and if the sum of the numbers written on those cards is equal to n, you will receive a luxurious prize. After each game, the cards will be returned to the bag.
Create a program that inputs the information of m types of cards in the bag and the number declared by the participants in g games, and outputs how many combinations of cards can receive luxury products in each game. please.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
m
a1 b1
a2 b2
::
am bm
g
n1
n2
::
ng
The number of card types m (1 β€ m β€ 7) on the first line, the integer ai (1 β€ ai β€ 100) written on the i-type card on the following m line, and the number bi (1 β€ bi β€ 10) Are given with a space delimiter.
The next line is given the number of games g (1 β€ g β€ 10), and the next g line is given the integer ni (1 β€ ni β€ 1,000) declared in game i.
The number of datasets does not exceed 100.
Output
For each input dataset, the i line prints the number of card combinations that will give you a gorgeous prize in Game i.
Example
Input
5
1 10
5 3
10 3
25 2
50 2
4
120
500
100
168
7
1 10
3 10
5 10
10 10
25 10
50 10
100 10
3
452
574
787
0
Output
16
0
12
7
9789
13658
17466 | instruction | 0 | 101,972 | 19 | 203,944 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
ans = []
while 1:
M = int(readline())
if M == 0:
break
P = [list(map(int, input().split())) for i in range(M)]
memo = {}
def dfs(i, rest):
if i == M:
return rest == 0
key = (i, rest)
if key in memo:
return memo[key]
res = 0
a, b = P[i]
for j in range(0, b+1):
if rest - j*a < 0:
break
res += dfs(i+1, rest - j*a)
memo[key] = res
return res
G = int(input())
for i in range(G):
ans.append(str(dfs(0, int(input()))))
write("\n".join(ans))
write("\n")
``` | output | 1 | 101,972 | 19 | 203,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's play the game using a bag containing several cards with integers written on it. In each game, participants first declare one of their favorite number n. Then, take out an appropriate number of cards from the bag at a time, and if the sum of the numbers written on those cards is equal to n, you will receive a luxurious prize. After each game, the cards will be returned to the bag.
Create a program that inputs the information of m types of cards in the bag and the number declared by the participants in g games, and outputs how many combinations of cards can receive luxury products in each game. please.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
m
a1 b1
a2 b2
::
am bm
g
n1
n2
::
ng
The number of card types m (1 β€ m β€ 7) on the first line, the integer ai (1 β€ ai β€ 100) written on the i-type card on the following m line, and the number bi (1 β€ bi β€ 10) Are given with a space delimiter.
The next line is given the number of games g (1 β€ g β€ 10), and the next g line is given the integer ni (1 β€ ni β€ 1,000) declared in game i.
The number of datasets does not exceed 100.
Output
For each input dataset, the i line prints the number of card combinations that will give you a gorgeous prize in Game i.
Example
Input
5
1 10
5 3
10 3
25 2
50 2
4
120
500
100
168
7
1 10
3 10
5 10
10 10
25 10
50 10
100 10
3
452
574
787
0
Output
16
0
12
7
9789
13658
17466
Submitted Solution:
```
from itertools import combinations as C
while True:
m = int(input())
if m==0:break
card = []
total = 0
for _ in range(m):
a, b = map(int, input().split())
card += [a]*b
total += b
g = int(input())
for _ in range(g):
ans = 0
duplicate = []
n = int(input())
for i in range(1, total+1):
for l in list(C(card, i)):
if sum(l)==n and not l in duplicate:
ans += 1
duplicate.append(l)
print(ans)
``` | instruction | 0 | 101,973 | 19 | 203,946 |
No | output | 1 | 101,973 | 19 | 203,947 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.
A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits.
Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.
Input
The first line contains a single integer n (2 β€ n β€ 10^5) standing for the length of numbers a and b.
The next two lines contain numbers a and b, each one on a separate line (10^{n-1} β€ a, b < 10^n).
Output
If it is impossible to win the jackpot, print a single integer -1.
Otherwise, the first line must contain the minimal possible number c of coins the player has to spend.
min(c, 10^5) lines should follow, i-th of them containing two integers d_i and s_i (1β€ d_iβ€ n - 1, s_i = Β± 1) denoting that on the i-th step the player should add s_i to the d_i-th and (d_i + 1)-st digits from the left (e. g. d_i = 1 means that two leading digits change while d_i = n - 1 means that there are two trailing digits which change).
Please notice that the answer may be very big and in case c > 10^5 you should print only the first 10^5 moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.
Examples
Input
3
223
322
Output
2
1 1
2 -1
Input
2
20
42
Output
2
1 1
1 1
Input
2
35
44
Output
-1
Note
In the first example, we can make a +1 operation on the two first digits, transforming number 223 into 333, and then make a -1 operation on the last two digits, transforming 333 into 322.
It's also possible to do these operations in reverse order, which makes another correct answer.
In the last example, one can show that it's impossible to transform 35 into 44. | instruction | 0 | 102,067 | 19 | 204,134 |
Tags: constructive algorithms, greedy, implementation, math
Correct Solution:
```
def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
cnt = sum(map(abs, x)) # prevbug: ftl
print(cnt)
cnt = min(cnt, 10 ** 5)
index = 0
def handle_zero_nine(cur_zero):
nonlocal cnt
nxt = index + 1
# cur_zero = True prevbug: preserved this line
while True:
if cur_zero and a[nxt + 1] != 9:
break
if not cur_zero and a[nxt + 1] != 0:
break
nxt += 1
cur_zero = not cur_zero
while nxt > index:
if cnt == 0:
break
if cur_zero:
print(nxt + 1, 1)
a[nxt] += 1
a[nxt + 1] += 1
else:
print(nxt + 1, -1)
a[nxt] -= 1
a[nxt + 1] -= 1
nxt -= 1
cnt -= 1
# print(a)
cur_zero = not cur_zero
while cnt > 0:
if a[index] == b[index]:
index += 1
continue
elif a[index] > b[index] and a[index + 1] == 0:
handle_zero_nine(True)
elif a[index] < b[index] and a[index + 1] == 9:
handle_zero_nine(False)
elif a[index] > b[index]:
print(index + 1, -1)
a[index] -= 1
a[index + 1] -= 1
cnt -= 1
# print(a)
elif a[index] < b[index]:
print(index + 1, 1)
a[index] += 1
a[index + 1] += 1
cnt -= 1
# print(a)
if __name__ == '__main__':
main()
``` | output | 1 | 102,067 | 19 | 204,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.
A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits.
Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.
Input
The first line contains a single integer n (2 β€ n β€ 10^5) standing for the length of numbers a and b.
The next two lines contain numbers a and b, each one on a separate line (10^{n-1} β€ a, b < 10^n).
Output
If it is impossible to win the jackpot, print a single integer -1.
Otherwise, the first line must contain the minimal possible number c of coins the player has to spend.
min(c, 10^5) lines should follow, i-th of them containing two integers d_i and s_i (1β€ d_iβ€ n - 1, s_i = Β± 1) denoting that on the i-th step the player should add s_i to the d_i-th and (d_i + 1)-st digits from the left (e. g. d_i = 1 means that two leading digits change while d_i = n - 1 means that there are two trailing digits which change).
Please notice that the answer may be very big and in case c > 10^5 you should print only the first 10^5 moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.
Examples
Input
3
223
322
Output
2
1 1
2 -1
Input
2
20
42
Output
2
1 1
1 1
Input
2
35
44
Output
-1
Note
In the first example, we can make a +1 operation on the two first digits, transforming number 223 into 333, and then make a -1 operation on the last two digits, transforming 333 into 322.
It's also possible to do these operations in reverse order, which makes another correct answer.
In the last example, one can show that it's impossible to transform 35 into 44.
Submitted Solution:
```
def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
cnt = sum(map(abs, x))
print(cnt)
cnt = min(cnt, 10 ** 5)
index = 0
def handle_zero_nine(cur_zero):
nonlocal cnt
nxt = index + 1
cur_zero = True
while True:
if cur_zero and a[nxt + 1] != 9:
break
if not cur_zero and a[nxt + 1] != 0:
break
nxt += 1
cur_zero = not cur_zero
while nxt > index:
if cnt == 0:
break
if cur_zero:
print(nxt + 1, 1)
a[nxt] += 1
a[nxt + 1] += 1
else:
print(nxt + 1, -1)
a[nxt] -= 1
a[nxt + 1] -= 1
nxt -= 1
cnt -= 1
cur_zero = not cur_zero
while cnt > 0:
if a[index] == b[index]:
index += 1
continue
elif a[index] > b[index] and a[index + 1] == 0:
handle_zero_nine(True)
elif a[index] < b[index] and a[index + 1] == 9:
handle_zero_nine(False)
elif a[index] > b[index]:
print(index + 1, -1)
a[index] -= 1
a[index + 1] -= 1
cnt -= 1
elif a[index] < b[index]:
print(index + 1, 1)
a[index] += 1
a[index + 1] += 1
cnt -= 1
if __name__ == '__main__':
main()
``` | instruction | 0 | 102,068 | 19 | 204,136 |
No | output | 1 | 102,068 | 19 | 204,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.
A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits.
Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.
Input
The first line contains a single integer n (2 β€ n β€ 10^5) standing for the length of numbers a and b.
The next two lines contain numbers a and b, each one on a separate line (10^{n-1} β€ a, b < 10^n).
Output
If it is impossible to win the jackpot, print a single integer -1.
Otherwise, the first line must contain the minimal possible number c of coins the player has to spend.
min(c, 10^5) lines should follow, i-th of them containing two integers d_i and s_i (1β€ d_iβ€ n - 1, s_i = Β± 1) denoting that on the i-th step the player should add s_i to the d_i-th and (d_i + 1)-st digits from the left (e. g. d_i = 1 means that two leading digits change while d_i = n - 1 means that there are two trailing digits which change).
Please notice that the answer may be very big and in case c > 10^5 you should print only the first 10^5 moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.
Examples
Input
3
223
322
Output
2
1 1
2 -1
Input
2
20
42
Output
2
1 1
1 1
Input
2
35
44
Output
-1
Note
In the first example, we can make a +1 operation on the two first digits, transforming number 223 into 333, and then make a -1 operation on the last two digits, transforming 333 into 322.
It's also possible to do these operations in reverse order, which makes another correct answer.
In the last example, one can show that it's impossible to transform 35 into 44.
Submitted Solution:
```
def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
cnt = sum(map(abs, x))
cnt = min(cnt, 10 ** 5)
index = 0
def handle_zero_nine(cur_zero):
nonlocal cnt
nxt = index + 1
cur_zero = True
while True:
if cur_zero and a[nxt + 1] != 9:
break
if not cur_zero and a[nxt + 1] != 0:
break
nxt += 1
cur_zero = not cur_zero
while nxt > index:
if cnt == 0:
break
if cur_zero:
print(nxt + 1, 1)
a[nxt] += 1
a[nxt + 1] += 1
else:
print(nxt + 1, -1)
a[nxt] -= 1
a[nxt + 1] -= 1
nxt -= 1
cnt -= 1
cur_zero = not cur_zero
while cnt > 0:
if a[index] == b[index]:
index += 1
continue
elif a[index] > b[index] and a[index + 1] == 0:
handle_zero_nine(True)
elif a[index] < b[index] and a[index + 1] == 9:
handle_zero_nine(False)
elif a[index] > b[index]:
print(index + 1, -1)
a[index] -= 1
a[index + 1] -= 1
cnt -= 1
elif a[index] < b[index]:
print(index + 1, 1)
a[index] += 1
a[index + 1] += 1
cnt -= 1
if __name__ == '__main__':
main()
``` | instruction | 0 | 102,069 | 19 | 204,138 |
No | output | 1 | 102,069 | 19 | 204,139 |
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 | 102,418 | 19 | 204,836 |
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 | 102,418 | 19 | 204,837 |
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 | 102,419 | 19 | 204,838 |
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=600):
"""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 | 102,419 | 19 | 204,839 |
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 | 102,420 | 19 | 204,840 |
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 | 102,420 | 19 | 204,841 |
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 | 102,421 | 19 | 204,842 |
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=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 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 | 102,421 | 19 | 204,843 |
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 | 102,422 | 19 | 204,844 |
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 | 102,422 | 19 | 204,845 |
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 | 102,423 | 19 | 204,846 |
No | output | 1 | 102,423 | 19 | 204,847 |
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 | 102,424 | 19 | 204,848 |
No | output | 1 | 102,424 | 19 | 204,849 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | instruction | 0 | 102,506 | 19 | 205,012 |
Tags: brute force, constructive algorithms
Correct Solution:
```
from sys import stdin
import operator
N = int(stdin.readline())
p = list(map(int, stdin.readline().strip().split(" ")))
teams = list(map(lambda x: 1 if x == "B" else -1, stdin.readline().strip()))
values = list(map(operator.mul, p, teams))
start = sum(filter(lambda x: max(x, 0), values))
# print(start)
total = start
best = start
for i in values:
total -= i
best = max(total, best)
total = start
for i in reversed(values):
total -= i
best = max(total, best)
# print(p, teams, values, best)
print(best)
``` | output | 1 | 102,506 | 19 | 205,013 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | instruction | 0 | 102,507 | 19 | 205,014 |
Tags: brute force, constructive algorithms
Correct Solution:
```
n, t = int(input()), list(map(int, input().split()))
b = [q * (d == 'B') for q, d in zip(t, input())]
y = v = sum(b)
x = u = sum(t) - v
for i in range(n):
u += 2 * b[i] - t[i]
x = max(x, u)
v += t[i] - 2 * b[i]
y = max(y, v)
print(max(x, y))
``` | output | 1 | 102,507 | 19 | 205,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | instruction | 0 | 102,508 | 19 | 205,016 |
Tags: brute force, constructive algorithms
Correct Solution:
```
n = int(input())
p = list(map(int, input().split()))
s = input()
ans = bob1 = bob2 = 0
for i in range(n):
if s[i] == 'B':
ans += p[i]
bob1 += p[i]
bob2 += p[i]
for i in range(n):
if s[i] == 'A':
bob1 += p[i]
else:
bob1 -= p[i]
ans = max(ans, bob1)
for i in reversed(range(n)):
if s[i] == 'A':
bob2 += p[i]
else:
bob2 -= p[i]
ans = max(ans, bob2)
print(ans)
``` | output | 1 | 102,508 | 19 | 205,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | instruction | 0 | 102,509 | 19 | 205,018 |
Tags: brute force, constructive algorithms
Correct Solution:
```
read = lambda: map(int, input().split())
n = int(input())
p = list(read())
a = [{'B': 1, 'A': 0}[i] for i in input()]
cur = sum(p[i] for i in range(n) if a[i])
ans = cur
b = a[:]
for i in range(n):
b[i] = int(not a[i])
if b[i]: cur += p[i]
else: cur -= p[i]
ans = max(ans, cur)
cur = sum(p[i] for i in range(n) if a[i])
b = a[:]
for i in range(n - 1, -1, -1):
b[i] = int(not a[i])
if b[i]: cur += p[i]
else: cur -= p[i]
ans = max(ans, cur)
print(ans)
``` | output | 1 | 102,509 | 19 | 205,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | instruction | 0 | 102,510 | 19 | 205,020 |
Tags: brute force, constructive algorithms
Correct Solution:
```
def main():
input()
pp = list(map(int, input().split()))
mask = [c == 'B' for c in input()]
s = t = sum(p for p, m in zip(pp, mask) if m)
res = [s]
for p, m in zip(pp, mask):
if m:
s -= p
else:
s += p
res.append(s)
pp.reverse()
mask.reverse()
for p, m in zip(pp, mask):
if m:
t -= p
else:
t += p
res.append(t)
print(max(res))
if __name__ == '__main__':
main()
``` | output | 1 | 102,510 | 19 | 205,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | instruction | 0 | 102,511 | 19 | 205,022 |
Tags: brute force, constructive algorithms
Correct Solution:
```
n, t = int(input()), list(map(int, input().split()))
b = [q * (d == 'B') for q, d in zip(t, input())]
v = sum(b)
u = sum(t) - v
s = max(u, v)
for i, j in zip(b, t):
u += 2 * i - j
v += j - 2 * i
s = max(u, v, s)
print(s)
``` | output | 1 | 102,511 | 19 | 205,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | instruction | 0 | 102,512 | 19 | 205,024 |
Tags: brute force, constructive algorithms
Correct Solution:
```
from itertools import accumulate
import math
n = int(input())
p = [int(x) for x in input().split()]
S1 = sum(p)
d = [x == 'A' for x in input()]
for i in range(n):
if d[i]: p[i] = -p[i]
prefix = list(accumulate([0] + p))
S = prefix[-1]
m, M = min(prefix), max(prefix)
print((S1 + max(S - 2*m, 2*M - S)) // 2)
``` | output | 1 | 102,512 | 19 | 205,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | instruction | 0 | 102,513 | 19 | 205,026 |
Tags: brute force, constructive algorithms
Correct Solution:
```
n = int(input())
p = list(map(int, input().split()))
s = input()
ans = 0
cur_orig = 0
for i in range(0, n):
if s[i] == 'B': cur_orig += p[i]
cur = cur_orig
ans = cur_orig
for i in range(0, n):
if s[i] == 'A':
cur += p[i]
ans = max(ans, cur)
else:
cur -= p[i]
cur = cur_orig
for i in range(n - 1, -1, -1):
if s[i] == 'A':
cur += p[i]
ans = max(ans, cur)
else:
cur -= p[i]
print(ans)
``` | output | 1 | 102,513 | 19 | 205,027 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
Submitted Solution:
```
n = input()
s = [int(x) for x in input().split(' ')]
g = input()
A = 0
B = 0
for i in range(len(g)):
if g[i] == 'A':
A += s[i]
else:
B += s[i]
startA, startB = A, B
maximum = B
for i in range(len(g)):
if g[i] == 'A':
A -= s[i]
B += s[i]
else:
A += s[i]
B -= s[i]
if B > maximum:
maximum = B
A, B = startA, startB
for i in reversed(range(len(g))):
if g[i] == 'A':
A -= s[i]
B += s[i]
else:
A += s[i]
B -= s[i]
if B > maximum:
maximum = B
print(maximum)
``` | instruction | 0 | 102,514 | 19 | 205,028 |
Yes | output | 1 | 102,514 | 19 | 205,029 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
Submitted Solution:
```
n = int(input())
powers = [int(i) for i in input().split()]
teams = input()
org_power = 0
for i in range(n):
if teams[i] == 'B':
org_power += powers[i]
max_power, power = org_power, org_power
for i in range(n):
if teams[i] == 'A':
power += powers[i]
max_power = max(max_power, power)
else:
power -= powers[i]
power = org_power
for i in range(n - 1, -1, -1):
if teams[i] == 'A':
power += powers[i]
max_power = max(max_power, power)
else:
power -= powers[i]
print(max_power)
``` | instruction | 0 | 102,515 | 19 | 205,030 |
Yes | output | 1 | 102,515 | 19 | 205,031 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
Submitted Solution:
```
n, t = int(input()), list(map(int, input().split()))
b = [q * (d == 'B') for q, d in zip(t, input())]
v = sum(b)
u = sum(t) - v
s = max(u, v)
for i, j in zip(b, t):
u += 2 * i - j
v += j - 2 * i
s = max(u, v, s)
print(s)
# Made By Mostafa_Khaled
``` | instruction | 0 | 102,516 | 19 | 205,032 |
Yes | output | 1 | 102,516 | 19 | 205,033 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
Submitted Solution:
```
n = input()
strength = input()
chars = input()
strength = strength.split(" ")
cost = 0
for k in range(0 , int(n)):
if chars[k] == 'B':
cost += int(strength[k])
temp = cost
temp_cost = temp
for j in range(0,int(n)):
if chars[j] == 'A':
temp_cost += int(strength[j])
else :
temp_cost -= int(strength[j])
cost = max(cost,temp_cost)
temp_cost = temp
for j in range(int(n) - 1 , 0 , -1):
if chars[j] == 'A':
temp_cost += int(strength[j])
else :
temp_cost -= int(strength[j])
cost = max(cost,temp_cost)
print(cost)
``` | instruction | 0 | 102,517 | 19 | 205,034 |
Yes | output | 1 | 102,517 | 19 | 205,035 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
Submitted Solution:
```
def A_B(start, finish):
return data[start] + data[finish] - sum(data[start + 1:finish])
n = int(input())
data = list(map(int, input().split()))
data1 = input()
data_i = []
ans1 = 0
during = 0
B = 0
help = []
help1 = []
for i in range(n):
if data1[i] == 'A':
data_i.append(i)
else:
B += data[i]
for i in range(1, len(data_i)):
help.append(A_B(data_i[i - 1], data_i[i]))
ans = 0
during = 0
for i in range(n):
if data1[i] == 'A':
during += data[i]
else:
ans = max(ans, during)
during = 0
ans = max(ans, during)
for i in range(n):
if data1[i] == 'B':
ans += data[i]
if n == 1:
print(data[0])
else:
print(max(B + max(help), ans))
``` | instruction | 0 | 102,518 | 19 | 205,036 |
No | output | 1 | 102,518 | 19 | 205,037 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
Submitted Solution:
```
n = int(input())
p = [int(x) for x in input().split(' ')]
k = input()
t = []
for u in k:
t.append(u)
a = 0
for i in range(0,n):
if t[i] == 'B':
a += p[i]
b = 0
c = 0
if t[0] == 'B' and t[n-1] == 'B':
pass
else:
for i in range(0,n):
if t[i] == 'A':
b += p[i]
elif t[i] == 'B':
break
p.reverse()
t.reverse()
for i in range(0,n):
if t[i] == 'A':
c += p[i]
elif t[i] == 'B':
break
print(a+max(b,c))
``` | instruction | 0 | 102,519 | 19 | 205,038 |
No | output | 1 | 102,519 | 19 | 205,039 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
Submitted Solution:
```
n = int(input())
A = list(map(int, input().split()))
s = input()
val = 0
for i,c in enumerate(s):
if c == 'B':
val += A[i]
A[i] = -1
subarray_val = val
max_val = val
for i in range(n+1):
if i < n and A[i] + subarray_val > subarray_val:
subarray_val += A[i]
else:
max_val = max(max_val, subarray_val)
subarray_val = val
print(max_val)
``` | instruction | 0 | 102,520 | 19 | 205,040 |
No | output | 1 | 102,520 | 19 | 205,041 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
Submitted Solution:
```
n = input()
strength = input()
chars = input()
strength = strength.split(" ")
cost = 0
for k in range(0 , int(n)):
if chars[k] == 'B':
cost += int(strength[k])
i = 0
while i < int(n) :
temp = chars
costpre = 0
#prefix
for j in range(0,i):
if temp[j] == 'A':
new = list(temp)
new[j] = 'B'
temp = ''.join(new)
elif temp[j] == 'B':
new = list(temp)
new[j] = 'A'
temp = ''.join(new)
for k in range(0 , int(n)):
if temp[k] == 'B':
costpre += int(strength[k])
#suffix
temp = chars
costsuf = 0
for j in range(int(n)-1,int(n)-i , 1):
if temp[j] == 'A' :
new = list(temp)
new[j] = 'B'
temp = ''.join(new)
elif temp[j] == 'B':
new = list(temp)
new[j] = 'A'
temp = ''.join(new)
for k in range(0 , int(n)):
if temp[k] == 'B':
costsuf += int(strength[k])
cost = max(cost , max(costsuf , costpre))
i += 1
print(cost)
``` | instruction | 0 | 102,521 | 19 | 205,042 |
No | output | 1 | 102,521 | 19 | 205,043 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.
Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101.
The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.
An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
Input
The first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.
Output
Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).
Examples
Input
????
Output
00
01
10
11
Input
1010
Output
10
Input
1?1
Output
01
11
Note
In the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes.
In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end. | instruction | 0 | 103,061 | 19 | 206,122 |
Tags: constructive algorithms, games, greedy
Correct Solution:
```
def evaluate(a):
c1 = a.count('1')
c0 = a.count('0')
n = len(a)
A = (n - 1) // 2
B = (n - 2) // 2
if c1 <= A:
return '00'
if c0 <= B:
return '11'
p1 = a.rfind('1')
p0 = a.rfind('0')
if p0 < p1:
return '01'
else:
return '10'
a = input()
x = []
x.append(evaluate(a.replace('?', '0')))
x.append(evaluate(a.replace('?', '1')))
n = len(a)
c1 = a.count('1')
c0 = a.count('0')
A = (n - 1) // 2
B = (n - 2) // 2
x.append(evaluate(a.replace('?', '0', B + 1 - c0).replace('?', '1')))
x.append(evaluate(a.replace('?', '1', A + 1 - c1).replace('?', '0')))
for ans in sorted(list(set(x))):
print(ans)
``` | output | 1 | 103,061 | 19 | 206,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap!
In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.
To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), β¦, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.
The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.
Input
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the number of shortcut positions, and the number of initial positions that need to be evaluated.
The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9). It is guaranteed that all shortcut positions are distinct.
The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 β€ a_i, b_i β€ 10^9) β the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.
Output
For each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.
Example
Input
3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
Output
LOSE
WIN
LOSE
WIN
LOSE | instruction | 0 | 103,101 | 19 | 206,202 |
Tags: data structures, games
Correct Solution:
```
def fun(n,m):
l1 = []
l2 = []
set1 = set()
var = 15 * 10 ** 8
for k1 in range(n):
x, y = map(int, input().split())
heappush(l1, (x,y))
heappush(l2, (y,x))
set1.add((x,y))
cx = cy = 0
X2=[]
Y2=[]
for i in range(2 * n):
tl = tr = var
tlp = trp = (var, var)
if l1:
tl = l1[0][0] - cx
tlp = (l1[0][0] - cx, l1[0][1] - cy)
if l2:
tr = l2[0][0] - cy
trp = (l2[0][0] - cy, l2[0][1] - cx)
if tlp < trp:
x, y = heappop(l1)
if tl < 0:
continue
cx+=tl;cy+=tl
assert x == cx
if y < cy:
X2.append(x)
cx += 1
else:
y, x = heappop(l2)
if tr < 0:
continue
cx+=tr;cy+=tr
assert y == cy
if x < cx:
Y2.append(y)
cy += 1
ans = []
from bisect import bisect_left
for k2 in range(m):
x, y = map(int, input().split())
if (x, y) in set1:
ans.append('LOSE')
continue
cs1 = bisect_left(X2, x)
cs2 = bisect_left(Y2, y)
if cs1 < len(X2) and X2[cs1] == x:
ans.append('WIN')
continue
if cs2 < len(Y2) and Y2[cs2] == y:
ans.append('WIN')
continue
if x-cs1==y-cs2:
ans.append('LOSE')
else:
ans.append('WIN')
print('\n'.join(map(str,ans)))
from heapq import *
a1, a2 = map(int, input().split())
fun(a1,a2)
``` | output | 1 | 103,101 | 19 | 206,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap!
In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.
To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), β¦, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.
The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.
Input
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the number of shortcut positions, and the number of initial positions that need to be evaluated.
The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9). It is guaranteed that all shortcut positions are distinct.
The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 β€ a_i, b_i β€ 10^9) β the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.
Output
For each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.
Example
Input
3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
Output
LOSE
WIN
LOSE
WIN
LOSE | instruction | 0 | 103,102 | 19 | 206,204 |
Tags: data structures, games
Correct Solution:
```
from heapq import *
from bisect import bisect_left
n, m = map(int, input().split())
inf = 15 * 10 ** 8
norm = []
rev = []
slow = set()
for _ in range(n):x, y = map(int, input().split());heappush(norm, (x,y));heappush(rev, (y,x));slow.add((x,y))
cx = cy = 0
skipX=[]
skipY=[]
for i in range(2 * n):
tl = tr = inf
tlp = trp = (inf, inf)
if norm:tl = norm[0][0] - cx;tlp = (norm[0][0] - cx, norm[0][1] - cy)
if rev:tr = rev[0][0] - cy;trp = (rev[0][0] - cy, rev[0][1] - cx)
if tlp < trp:
x, y = heappop(norm)
if tl < 0:continue
cx+=tl;cy+=tl
assert x == cx
if y < cy:skipX.append(x);cx += 1
else:
y, x = heappop(rev)
if tr < 0:
continue
cx+=tr;cy+=tr
assert y == cy
if x < cx:
skipY.append(y)
cy += 1
out = []
for _ in range(m):
x, y = map(int, input().split())
if (x, y) in slow: out.append('LOSE'); continue
csx = bisect_left(skipX, x); csy = bisect_left(skipY, y)
if csx < len(skipX) and skipX[csx] == x: out.append('WIN'); continue
if csy < len(skipY) and skipY[csy] == y: out.append('WIN'); continue
out.append('LOSE' if x-csx==y-csy else 'WIN')
print('\n'.join(map(str,out)))
``` | output | 1 | 103,102 | 19 | 206,205 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap!
In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.
To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), β¦, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.
The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.
Input
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the number of shortcut positions, and the number of initial positions that need to be evaluated.
The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9). It is guaranteed that all shortcut positions are distinct.
The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 β€ a_i, b_i β€ 10^9) β the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.
Output
For each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.
Example
Input
3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
Output
LOSE
WIN
LOSE
WIN
LOSE | instruction | 0 | 103,103 | 19 | 206,206 |
Tags: data structures, games
Correct Solution:
```
from heapq import *;from bisect import bisect_left
n, m = map(int, input().split());inf = 15 * 10 ** 8;norm = [];rev = [];slow = set();cx = cy = 0;skipX=[];skipY=[];out = []
for _ in range(n):x, y = map(int, input().split());heappush(norm, (x,y));heappush(rev, (y,x));slow.add((x,y))
for i in range(2 * n):
tl = tr = inf;tlp = trp = (inf, inf)
if norm:tl = norm[0][0] - cx;tlp = (norm[0][0] - cx, norm[0][1] - cy)
if rev:tr = rev[0][0] - cy;trp = (rev[0][0] - cy, rev[0][1] - cx)
if tlp < trp:
x, y = heappop(norm)
if tl < 0:continue
cx+=tl;cy+=tl
assert x == cx
if y < cy:skipX.append(x);cx += 1
else:
y, x = heappop(rev)
if tr < 0: continue
cx+=tr;cy+=tr
assert y == cy
if x < cx:skipY.append(y); cy += 1
for _ in range(m):
x, y = map(int, input().split())
if (x, y) in slow: out.append('LOSE'); continue
csx = bisect_left(skipX, x); csy = bisect_left(skipY, y)
if csx < len(skipX) and skipX[csx] == x: out.append('WIN'); continue
if csy < len(skipY) and skipY[csy] == y: out.append('WIN'); continue
out.append('LOSE' if x-csx==y-csy else 'WIN')
print('\n'.join(map(str,out)))
``` | output | 1 | 103,103 | 19 | 206,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap!
In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.
To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), β¦, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.
The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.
Input
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the number of shortcut positions, and the number of initial positions that need to be evaluated.
The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9). It is guaranteed that all shortcut positions are distinct.
The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 β€ a_i, b_i β€ 10^9) β the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.
Output
For each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.
Example
Input
3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
Output
LOSE
WIN
LOSE
WIN
LOSE | instruction | 0 | 103,104 | 19 | 206,208 |
Tags: data structures, games
Correct Solution:
```
import sys
input = sys.stdin.readline
from heapq import *
n, m = map(int, input().split())
inf = 15 * 10 ** 8
norm = []
rev = []
slow = set()
for _ in range(n):
x, y = map(int, input().split())
heappush(norm, (x,y))
heappush(rev, (y,x))
slow.add((x,y))
cx = cy = 0
skipX=[]
skipY=[]
for i in range(2 * n):
tl = tr = inf
tlp = trp = (inf, inf)
if norm:
tl = norm[0][0] - cx
tlp = (norm[0][0] - cx, norm[0][1] - cy)
if rev:
tr = rev[0][0] - cy
trp = (rev[0][0] - cy, rev[0][1] - cx)
if tlp < trp:
x, y = heappop(norm)
if tl < 0:
continue
cx+=tl;cy+=tl
assert x == cx
if y < cy:
skipX.append(x)
cx += 1
else:
y, x = heappop(rev)
if tr < 0:
continue
cx+=tr;cy+=tr
assert y == cy
if x < cx:
skipY.append(y)
cy += 1
out = []
from bisect import bisect_left
for _ in range(m):
x, y = map(int, input().split())
if (x, y) in slow:
out.append('LOSE')
continue
csx = bisect_left(skipX, x)
csy = bisect_left(skipY, y)
if csx < len(skipX) and skipX[csx] == x:
out.append('WIN')
continue
if csy < len(skipY) and skipY[csy] == y:
out.append('WIN')
continue
if x-csx==y-csy:
out.append('LOSE')
else:
out.append('WIN')
print('\n'.join(map(str,out)))
``` | output | 1 | 103,104 | 19 | 206,209 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap!
In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.
To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), β¦, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.
The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.
Input
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the number of shortcut positions, and the number of initial positions that need to be evaluated.
The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9). It is guaranteed that all shortcut positions are distinct.
The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 β€ a_i, b_i β€ 10^9) β the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.
Output
For each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.
Example
Input
3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
Output
LOSE
WIN
LOSE
WIN
LOSE
Submitted Solution:
```
import sys
input = sys.stdin.readline
from heapq import *
n, m = map(int, input().split())
inf = 15 * 10 ** 8
norm = []
rev = []
slow = set()
for _ in range(n):
x, y = map(int, input().split())
heappush(norm, (x,y))
heappush(rev, (y,x))
slow.add((x,y))
cx = cy = 0
skipX=[]
skipY=[]
for i in range(2 * n):
tl = tr = inf
if norm:
tl = norm[0][0] - cx
if rev:
tr = rev[0][0] - cy
if tl < tr:
x, y = heappop(norm)
if tl < 0:
continue
cx+=tl;cy+=tl
assert x == cx
if y < cy:
skipX.append(x)
cx += 1
else:
y, x = heappop(rev)
if tr < 0:
continue
cx+=tr;cy+=tr
assert y == cy
if x < cx:
skipY.append(y)
cy += 1
out = []
from bisect import bisect_left
for _ in range(m):
x, y = map(int, input().split())
if (x, y) in slow:
out.append('LOSE')
continue
csx = bisect_left(skipX, x)
csy = bisect_left(skipY, y)
if csx < len(skipX) and skipX[csx] == x:
out.append('WIN')
continue
if csy < len(skipY) and skipY[csy] == y:
out.append('WIN')
continue
if x-csx==y-csy:
out.append('LOSE')
else:
out.append('WIN')
print('\n'.join(map(str,out)))
``` | instruction | 0 | 103,105 | 19 | 206,210 |
No | output | 1 | 103,105 | 19 | 206,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap!
In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.
To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), β¦, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.
The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.
Input
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the number of shortcut positions, and the number of initial positions that need to be evaluated.
The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9). It is guaranteed that all shortcut positions are distinct.
The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 β€ a_i, b_i β€ 10^9) β the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.
Output
For each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.
Example
Input
3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
Output
LOSE
WIN
LOSE
WIN
LOSE
Submitted Solution:
```
def ii():
return tuple(int(s) for s in input().split())
if __name__ == '__main__':
n, m = ii()
shortcuts = []
queries = []
for _ in range(n):
shortcuts.append(ii())
for _ in range(m):
queries.append(ii())
shortcuts_set = set(shortcuts)
delta = 0
result = [None] * len(queries)
x_list = []
y_list = []
for i, (x, y) in enumerate(shortcuts):
x_list.append((x, 0, i))
y_list.append((y, 0, i))
for i, (x, y) in enumerate(queries):
if (x, y) in shortcuts_set:
result[i] = False
else:
x_list.append((x, 1, i))
y_list.append((y, 1, i))
x_list.sort(reverse=True)
y_list.sort(reverse=True)
#print(x_list)
#print(y_list)
delta = 0
while x_list or y_list:
#print(x_list[-1] if x_list else None, y_list[-1] if y_list else None)
if x_list and (not y_list or x_list[-1][0] + delta < y_list[-1][0] or (x_list[-1][0] + delta == y_list[-1][0] and y_list[-1][1] == 1)):
if x_list[-1][1] == 1:
x, _, i = x_list.pop()
if result[i] is None:
y = queries[i][1]
if x + delta == y:
result[i] = False
else:
result[i] = True
#print("result0", i, result[i])
continue
if x_list and (not y_list or x_list[-1][0] + delta <= y_list[-1][0]):
if x_list[-1][1] == 0:
x, _, i = x_list[-1]
if shortcuts[i][1] > x + delta:
x_list.pop()
continue
if y_list and (not x_list or x_list[-1][0] + delta > y_list[-1][0]):
if y_list[-1][1] == 1:
y, _, i = y_list.pop()
if result[i] is None:
x = queries[i][0]
if x + delta == y:
result[i] = False
else:
result[i] = True
#print("result1", i, result[i])
continue
if y_list and (not x_list or x_list[-1][0] + delta >= y_list[-1][0]):
if y_list[-1][1] == 0:
y, _, i = y_list[-1]
if shortcuts[i][0] + delta > y:
y_list.pop()
continue
if x_list and y_list and (x_list[-1][0] + delta == y_list[-1][0] and x_list[-1][1] == y_list[-1][1] == 0):
x, _, _ = x_list.pop()
y, _, _ = y_list.pop()
while x_list and x_list[-1][0] == x:
_, t, i = x_list.pop()
if t == 1:
if result[i] is None:
result[i] = True
#print("result2", i, result[i])
while y_list and y_list[-1][0] == y:
_, t, i = y_list.pop()
if t == 1:
if result[i] is None:
result[i] = True
#print("result3", i, result[i])
#print("next lose", x + 1, y + 1)
elif x_list and (not y_list or x_list[-1][0] + delta < y_list[-1][0] or y_list[-1][1] == 1):
x, _, _ = x_list.pop()
while x_list and x_list[-1][0] == x:
_, t, i = x_list.pop()
if t == 1:
if result[i] is None:
result[i] = True
#print("result4", i, result[i])
delta -= 1
#print("next lose", x + 1, x + 1 + delta)
else:
y, _, _ = y_list.pop()
while y_list and y_list[-1][0] == y:
_, t, i = y_list.pop()
if t == 1:
if result[i] is None:
result[i] = True
#print("result5", i, result[i])
delta += 1
#print("next lose", y + 1 - delta, y + 1)
for r in result:
print("WIN" if r else "LOSE")
``` | instruction | 0 | 103,106 | 19 | 206,212 |
No | output | 1 | 103,106 | 19 | 206,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap!
In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.
To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), β¦, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.
The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.
Input
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the number of shortcut positions, and the number of initial positions that need to be evaluated.
The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9). It is guaranteed that all shortcut positions are distinct.
The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 β€ a_i, b_i β€ 10^9) β the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.
Output
For each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.
Example
Input
3 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
Output
LOSE
WIN
LOSE
WIN
LOSE
Submitted Solution:
```
def ii():
return tuple(int(s) for s in input().split())
if __name__ == '__main__':
n, m = ii()
shortcuts = []
queries = []
for _ in range(n):
shortcuts.append(ii())
for _ in range(m):
queries.append(ii())
shortcuts_set = set(shortcuts)
delta = 0
result = [None] * len(queries)
x_list = []
y_list = []
for i, (x, y) in enumerate(shortcuts):
x_list.append((x, 0, i))
y_list.append((y, 0, i))
for i, (x, y) in enumerate(queries):
if (x, y) in shortcuts_set:
result[i] = False
else:
x_list.append((x, 1, i))
y_list.append((y, 1, i))
x_list.sort(reverse=True)
y_list.sort(reverse=True)
#print(x_list)
#print(y_list)
delta = 0
while x_list or y_list:
#print(x_list[-1] if x_list else None, y_list[-1] if y_list else None)
if x_list and (not y_list or x_list[-1][0] + delta < y_list[-1][0] or (x_list[-1][0] + delta == y_list[-1][0] and y_list[-1][1] == 1)):
if x_list[-1][1] == 1:
x, _, i = x_list.pop()
if result[i] is None:
y = queries[i][1]
if x + delta == y:
result[i] = False
else:
result[i] = True
#print("result0", i, result[i])
continue
if x_list and (not y_list or x_list[-1][0] + delta <= y_list[-1][0]):
if x_list[-1][1] == 0:
x, _, i = x_list[-1]
if shortcuts[i][1] > x + delta:
x_list.pop()
continue
if y_list and (not x_list or x_list[-1][0] + delta > y_list[-1][0]):
if y_list[-1][1] == 1:
y, _, i = y_list.pop()
if result[i] is None:
x = queries[i][0]
if x + delta == y:
result[i] = False
else:
result[i] = True
#print("result1", i, result[i])
continue
if y_list and (not x_list or x_list[-1][0] + delta >= y_list[-1][0]):
if y_list[-1][1] == 0:
y, _, i = y_list[-1]
if shortcuts[i][0] + delta > y:
y_list.pop()
continue
if x_list and y_list and (x_list[-1][0] + delta == y_list[-1][0] and x_list[-1][1] == y_list[-1][1] == 0):
x, _, _ = x_list.pop()
y, _, _ = y_list.pop()
while x_list and x_list[-1][0] == x:
_, t, i = x_list.pop()
if t == 1:
if result[i] is None:
result[i] = True
#print("result2", i, result[i])
while y_list and y_list[-1][0] == y:
_, t, i = y_list.pop()
if t == 1:
if result[i] is None:
result[i] = True
#print("result3", i, result[i])
#print("next lose", x + 1, y + 1)
elif x_list and x_list[-1][1] == 0 and (not y_list or x_list[-1][0] + delta < y_list[-1][0] or y_list[-1][1] == 1):
x, _, _ = x_list.pop()
while x_list and x_list[-1][0] == x:
_, t, i = x_list.pop()
if t == 1:
if result[i] is None:
result[i] = True
#print("result4", i, result[i])
delta -= 1
#print("next lose", x + 1, x + 1 + delta)
else:
y, _, _ = y_list.pop()
while y_list and y_list[-1][0] == y:
_, t, i = y_list.pop()
if t == 1:
if result[i] is None:
result[i] = True
#print("result5", i, result[i])
delta += 1
#print("next lose", y + 1 - delta, y + 1)
for r in result:
if r is None:
print("???")
else:
print("WIN" if r is True else "LOSE")
``` | instruction | 0 | 103,107 | 19 | 206,214 |
No | output | 1 | 103,107 | 19 | 206,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second | instruction | 0 | 103,125 | 19 | 206,250 |
Tags: combinatorics, constructive algorithms
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
#n, k = map(int, input().split())
n,m,x1,y1,x2,y2 = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
x, y = abs(x2-x1), abs(y2-y1)
x, y = min(x,y), max(x,y)
if [x,y] in [[0,0], [0,1], [0,2], [0,3], [0,4],
[1,1], [1,2], [1,3], [1,4],
[2,2], [2,3], [2,4],
[3,3]]:
print("First")
else:
print("Second")
``` | output | 1 | 103,125 | 19 | 206,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second | instruction | 0 | 103,126 | 19 | 206,252 |
Tags: combinatorics, constructive algorithms
Correct Solution:
```
n,m,x1,y1,x2,y2 = map(int, input().split())
n = abs(x1 - x2)
m = abs(y1 - y2)
if n > 4 or m > 4:
print("Second")
elif n <= 3 and m <= 3:
print("First")
elif min(n, m) <= 2:
print("First")
else:
print("Second")
``` | output | 1 | 103,126 | 19 | 206,253 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second | instruction | 0 | 103,127 | 19 | 206,254 |
Tags: combinatorics, constructive algorithms
Correct Solution:
```
# METO Bot 0.9.9
n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[1]<5 and a[0]+a[1]<7 else "Second")
``` | output | 1 | 103,127 | 19 | 206,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second | instruction | 0 | 103,128 | 19 | 206,256 |
Tags: combinatorics, constructive algorithms
Correct Solution:
```
n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[1]<5 and a[0]+a[1]<7 else "Second")
``` | output | 1 | 103,128 | 19 | 206,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second | instruction | 0 | 103,129 | 19 | 206,258 |
Tags: combinatorics, constructive algorithms
Correct Solution:
```
# METO Bot 0.9.9.1
n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[1]<5 and a[0]+a[1]<7 else "Second")
``` | output | 1 | 103,129 | 19 | 206,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second | instruction | 0 | 103,130 | 19 | 206,260 |
Tags: combinatorics, constructive algorithms
Correct Solution:
```
n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[1]<5 and a[0]+a[1]<7 else "Second")
# Made By Mostafa_Khaled
``` | output | 1 | 103,130 | 19 | 206,261 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second
Submitted Solution:
```
n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[0]<5 and a[0]+a[1]<7 else "Second")
``` | instruction | 0 | 103,131 | 19 | 206,262 |
No | output | 1 | 103,131 | 19 | 206,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two players play a game. The game is played on a rectangular board with n Γ m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 β the board sizes and the coordinates of the first and second chips, correspondingly (1 β€ n, m β€ 100; 2 β€ n Γ m; 1 β€ x1, x2 β€ n; 1 β€ y1, y2 β€ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second
Submitted Solution:
```
n,m,x1,y1,x2,y2 = map(int, input().split())
n = abs(x1 - x2)
m = abs(y1 - y2)
if n > 2 or m > 2:
print("Second")
elif n == 2 and m == 2:
print("Second")
else:
print("First")
``` | instruction | 0 | 103,132 | 19 | 206,264 |
No | output | 1 | 103,132 | 19 | 206,265 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.
Input
The first line contains integer n (1 β€ n β€ 3Β·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 β€ ai β€ 5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces.
Output
If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs.
Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.
Examples
Input
3
20 30 10 30 20 10
Output
4 2
1 5
6 3
Input
1
1 2
Output
-1 | instruction | 0 | 103,165 | 19 | 206,330 |
Tags: constructive algorithms, sortings
Correct Solution:
```
from sys import stdin, stdout
import math,sys
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict,Counter
from os import path
import bisect as bi
import heapq
mod=10**9+7
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
#------------------Sublime--------------------------------------#
sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def inp():return (int(input()))
def minp():return(map(int,input().split()))
else:
#------------------PYPY FAst I/o--------------------------------#
def inp():return (int(stdin.readline()))
def minp():return(map(int,stdin.readline().split()))
####### ---- Start Your Program From Here ---- #######
n=inp()
a=list(minp())
d=Counter(a)
flag=0
for keys in d:
if d[keys]&1:
flag=1
break
if flag:
print(-1)
exit(0)
d={}
for i in range(2*n):
try:
d[a[i]].append(i+1)
except:
d[a[i]]=[i+1]
for keys in d:
print(*d[keys])
``` | output | 1 | 103,165 | 19 | 206,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.
Input
The first line contains integer n (1 β€ n β€ 3Β·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 β€ ai β€ 5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces.
Output
If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs.
Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.
Examples
Input
3
20 30 10 30 20 10
Output
4 2
1 5
6 3
Input
1
1 2
Output
-1
Submitted Solution:
```
f=open("input.txt", "r")
text = f.readlines()
f.close()
n = int(text[0])
cards = [int(c) for c in text[1].split()]
f = open("output.txt", "w")
if len(set(cards)) > n:
f.write(str(-1))
exit()
pairs = []
bruhcards = sorted(set(cards))
for x in bruhcards:
pairs.append(cards.index(x)+1)
cards[cards.index(x)] += 5000
pairs.append(cards.index(x)+1)
cards[cards.index(x)] += 5000
pairsinpairs = [pairs[i:i + 2] for i in range(0, len(pairs), 2)]
for pair in pairsinpairs:
f.write(' '.join([str(bruhytho) for bruhytho in pair]))
f.write('\n')
f.close()
``` | instruction | 0 | 103,166 | 19 | 206,332 |
No | output | 1 | 103,166 | 19 | 206,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.
Input
The first line contains integer n (1 β€ n β€ 3Β·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 β€ ai β€ 5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces.
Output
If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs.
Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.
Examples
Input
3
20 30 10 30 20 10
Output
4 2
1 5
6 3
Input
1
1 2
Output
-1
Submitted Solution:
```
import os
inputFile=open("input.txt",'r')
outputFile=open("output.txt",'w')
from collections import defaultdict
n=int(inputFile.readline())
hashTable=defaultdict(list)
array=list(map(int,inputFile.readline().split()))
ans=[]
for idx,val in enumerate(array,1):
hashTable[val].append(idx)
for i in hashTable.values():
if len(i)%2!=0:
os.remove("output.txt")
outputFile=open("output.txt",'w')
outputFile.writelines("-1")
break
else:
outputFile.writelines((" ".join([str(i)for i in i])+"\n"))
``` | instruction | 0 | 103,167 | 19 | 206,334 |
No | output | 1 | 103,167 | 19 | 206,335 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.
Input
The first line contains integer n (1 β€ n β€ 3Β·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 β€ ai β€ 5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces.
Output
If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs.
Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.
Examples
Input
3
20 30 10 30 20 10
Output
4 2
1 5
6 3
Input
1
1 2
Output
-1
Submitted Solution:
```
import re
import sys
exit=sys.exit
from bisect import bisect_left as bsl,bisect_right as bsr
from collections import Counter,defaultdict as ddict,deque
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=enumerate
ri=lambda:int(rln())
ris=lambda:list(map(int,rfs()))
rln=sys.stdin.readline
rl=lambda:rln().rstrip('\n')
rfs=lambda:rln().split()
cat=''.join
catn='\n'.join
mod=1000000007
d4=[(0,-1),(1,0),(0,1),(-1,0)]
d8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
########################################################################
inp=list(open('input.txt'))
out=open('output.txt','w')
n=int(inp[0])
a=list(map(int,inp[1].split()))
d=ddict(set)
for i in range(2*n):
d[a[i]].add(i)
ans=[]
for x in d:
if len(d[x])%2:
out.write(str(-1)+'\n')
exit()
while d[x]:
j=d[x].pop()
i=d[x].pop()
ans.append(f'{1+i} {1+j}')
out.write(cat(ans))
``` | instruction | 0 | 103,168 | 19 | 206,336 |
No | output | 1 | 103,168 | 19 | 206,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.
Input
The first line contains integer n (1 β€ n β€ 3Β·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 β€ ai β€ 5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces.
Output
If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs.
Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.
Examples
Input
3
20 30 10 30 20 10
Output
4 2
1 5
6 3
Input
1
1 2
Output
-1
Submitted Solution:
```
import sys
try:
sys.exit(0)
f = open('./output.txt', 'w')
f.write('0')
f.close()
f = open('./input.txt', 'r')
n = int(f.readline())
a = list(map(int, f.readline().split()))
f.close()
for i in range(1, 2*n+1):
a[i-1] = [a[i-1], i]
a.sort(key=lambda x: x[0])
flag = True
ans = []
for i in range(1, 2*n+1, 2):
if a[i][0] == a[i-1][0]:
ans.append((a[i-1][1], a[i][1]))
else:
flag = False
break
f = open('./output.txt', 'w')
if flag:
for it in ans:
f.write('{} {}\n'.format(*it))
else:
f.write('-1')
f.close()
except SystemExit:
pass
``` | instruction | 0 | 103,169 | 19 | 206,338 |
No | output | 1 | 103,169 | 19 | 206,339 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.