message stringlengths 2 67k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 463 109k | cluster float64 19 19 | __index_level_0__ int64 926 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. | instruction | 0 | 7,210 | 19 | 14,420 |
Tags: math, number theory
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left)/ 2)
# Check if middle element is
# less than or equal to key
if (arr[mid]<=key):
count = mid+1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater( arr,n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
for i in range(int(input())):
a,b=map(int,input().split())
#c=a*b
l=int((a*b)**(1/3)+0.5)
if l**3==a*b and a%l==0 and b%l==0:
print("YES")
else:
print("NO")
``` | output | 1 | 7,210 | 19 | 14,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. | instruction | 0 | 7,211 | 19 | 14,422 |
Tags: math, number theory
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
from math import pow
# ------------------------------
def main():
for _ in range(N()):
a, b = RL()
mt = a*b
res = round(pow(mt, 1/3))
if res**3==mt and a%res==0 and b%res==0:
print('Yes')
else:
print('No')
if __name__ == "__main__":
main()
``` | output | 1 | 7,211 | 19 | 14,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. | instruction | 0 | 7,212 | 19 | 14,424 |
Tags: math, number theory
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left)/ 2)
# Check if middle element is
# less than or equal to key
if (arr[mid]<=key):
count = mid+1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater( arr,n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
for i in range(int(input())):
a,b=map(int,input().split())
c=a*b
l=int(c**(1/3)+0.5)
if l**3==a*b and a%l==0 and b%l==0:
print("YES")
else:
print("NO")
``` | output | 1 | 7,212 | 19 | 14,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. | instruction | 0 | 7,213 | 19 | 14,426 |
Tags: math, number theory
Correct Solution:
```
import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
for _ in range(int(input())):
a, b = map(int, input().split())
q = a * b
t = round(q ** (1 / 3))
if t * t * t == q and a % t == b % t == 0:
print('YES')
else:
print('NO')
``` | output | 1 | 7,213 | 19 | 14,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
def gcd(a, b):
if a > b:
a, b = b, a
if b % a==0:
return a
return gcd(b % a, a)
def process(a, b):
g = gcd(a, b)
r = a//g
s = b//g
if g % r != 0:
return 'No'
g = g//r
if g % s != 0:
return 'No'
G3 = g//s
G = round(G3**(1/3))
cube = False
for i in range(10):
if (G-i)**3==G3 or (G+i)**3==G3:
cube = True
break
if not cube:
return 'No'
return 'Yes'
n = int(input())
for i in range(n):
a, b = [int(x) for x in input().split()]
sys.stdout.write(process(a, b)+'\n')
``` | instruction | 0 | 7,214 | 19 | 14,428 |
Yes | output | 1 | 7,214 | 19 | 14,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
Submitted Solution:
```
import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for tc in range(t):
a, b = map(int, input().split())
cbrt = round(pow(a*b, 1/3))
if pow(cbrt, 3) == a*b:
if a % cbrt == b % cbrt == 0:
print("Yes")
continue
print("No")
``` | instruction | 0 | 7,215 | 19 | 14,430 |
Yes | output | 1 | 7,215 | 19 | 14,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left)/ 2)
# Check if middle element is
# less than or equal to key
if (arr[mid]<=key):
count = mid+1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater( arr,n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
for i in range(int(input())):
a,b=map(int,input().split())
l=(a*b)**(Fraction(1,3))+0.5
if int(l)**3==a*b and a%l==0 and b%l==0:
print("YES")
else:
print("NO")
``` | instruction | 0 | 7,216 | 19 | 14,432 |
No | output | 1 | 7,216 | 19 | 14,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
Submitted Solution:
```
primes = []
M = 10**9
for p in range(2, M):
if p*p > M:
break
is_prime = True
for p2 in primes:
if p2*p2 > p:
break
if p % p2==0:
is_prime = False
break
if is_prime:
primes.append(p)
def factor(n):
d = {}
for p in primes:
if p*p > n:
break
if n % p==0:
c = 0
while n % p==0:
c+=1
n = n//p
d[p] = c
if n > 1:
d[n] = 1
return d
def process(a, b):
d1 = factor(a)
d2 = factor(b)
L = []
for p in d1:
L.append(p)
for p in d2:
if p not in d1:
L.append(p)
for p in L:
x = d1.get(p, 0)
y = d2.get(p, 0)
if (x+y) % 3 != 0:
return 'No'
if x < 2*y or y < 2*x:
return 'No'
return 'Yes'
n = int(input())
for i in range(n):
a, b = [int(x) for x in input().split()]
print(process(a, b))
``` | instruction | 0 | 7,217 | 19 | 14,434 |
No | output | 1 | 7,217 | 19 | 14,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
Submitted Solution:
```
n = int(input())
for _ in range (n):
a, b = map(int, input().split())
p = a * b
c = int(round(p ** .333))
if c ** 3 == p and a % c == 0 and b % c == 0:
print("Yes")
else:
print("No")
``` | instruction | 0 | 7,218 | 19 | 14,436 |
No | output | 1 | 7,218 | 19 | 14,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
Input
In the first string, the number of games n (1 β€ n β€ 350000) is given.
Each game is represented by a pair of scores a, b (1 β€ a, b β€ 109) β the results of Slastyona and Pushok, correspondingly.
Output
For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
Example
Input
6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000
Output
Yes
Yes
Yes
No
No
Yes
Note
First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.
The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
Submitted Solution:
```
import math
t = int(input())
for tc in range(t):
a, b = map(int, input().split())
if not round(pow(a*b, 1/3), 2) ** 3 != a*b:
if a % round(pow(a*b, 1/3), 2) == b % round(pow(a*b, 1/3), 2) == 0:
print("Yes")
continue
print("No")
``` | instruction | 0 | 7,219 | 19 | 14,438 |
No | output | 1 | 7,219 | 19 | 14,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | instruction | 0 | 7,266 | 19 | 14,532 |
Tags: dp
Correct Solution:
```
from __future__ import print_function
from queue import Queue
import sys
import math
import os.path
# CONFIG
sys.setrecursionlimit(10**9)
# LOG
def log(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# INPUT
def ni():
return map(int, input().split())
def nio(offset):
return map(lambda x: int(x) + offset, input().split())
def nia():
return list(map(int, input().split()))
# CONVERT
def toString(aList, sep=" "):
return sep.join(str(x) for x in aList)
def mapInvertIndex(aList):
return {k: v for v, k in enumerate(aList)}
def countMap(arr):
m = {}
for x in arr:
m[x] = m.get(x,0) + 1
return m
def sortId(arr):
return sorted(range(arr), key=lambda k: arr[k])
# MAIN
n, k = ni()
c = nia()
f = nia()
h = [0] + (nia())
cc = countMap(c)
cf = countMap(f)
n1 = n+1
k1 = k+1
nk1 = n*k+1
dp = [[0]*nk1 for _ in range(n1)]
for ni in range(1,n1):
for ki in range(1,nk1):
mficount = min(k,ki) + 1
for kii in range(mficount):
# log(ni,ki, kii, dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
dp[ni][ki] = max(dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
# log(dp[ni])
# log(n,k)
# log("c", cc)
# log("f", cf)
# log("h", h)
# log(dp)
res = 0
for fk,fv in cf.items():
# log(fk, fv, cc.get(fk,0))
res += dp[fv][cc.get(fk,0)]
print(res)
``` | output | 1 | 7,266 | 19 | 14,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | instruction | 0 | 7,267 | 19 | 14,534 |
Tags: dp
Correct Solution:
```
def solve():
n, k = map(int, input().split())
c = list(map(int, input().split()))
f = list(map(int, input().split()))
h = list(map(int, input().split()))
cnt = {}
for i in c:
cnt[i] = cnt.get(i, 0) + 1
likecolor = {}
for i in range(n):
likecolor.setdefault(f[i], []).append(i)
cnt[f[i]] = cnt.get(f[i], 0)
ans = 0
for key, v in likecolor.items():
n1 = len(v)
if cnt[key] >= n1 * k:
ans += n1 * h[k - 1]
continue
dp = [[-float("INF")] * (cnt[key]+1) for _ in range(n1 + 1)]
dp[0][0] = 0
for i in range(n1):
j = i + 1
for e in range(cnt[key] + 1):
dp[j][e] = max(dp[j][e], dp[i][e])
for w in range(e + 1, min(cnt[key] + 1, e + k + 1)):
dp[j][w] = max(dp[i][e] + h[w - e - 1], dp[j][w])
ans += dp[n1][cnt[key]]
print(ans)
solve()
``` | output | 1 | 7,267 | 19 | 14,535 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | instruction | 0 | 7,268 | 19 | 14,536 |
Tags: dp
Correct Solution:
```
from __future__ import print_function
from queue import Queue
import sys
import math
import os.path
sys.setrecursionlimit(10**9)
def log(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def ni():
return map(int, input().split())
def nio(offset):
return map(lambda x: int(x) + offset, input().split())
def nia():
return list(map(int, input().split()))
def toString(aList, sep=" "):
return sep.join(str(x) for x in aList)
def mapInvertIndex(aList):
return {k: v for v, k in enumerate(aList)}
def countMap(arr):
m = {}
for x in arr:
m[x] = m.get(x,0) + 1
return m
def sortId(arr):
return sorted(range(arr), key=lambda k: arr[k])
# MAIN
n, k = ni()
c = nia()
f = nia()
h = nia()
h.insert(0,0)
cc = countMap(c)
cf = countMap(f)
n1 = n+1
k1 = k+1
nk1 = n*k+1
dp = [[0]*nk1 for _ in range(n1)]
for ni in range(1,n1):
for ki in range(1,nk1):
mficount = min(k,ki) + 1
for kii in range(mficount):
dp[ni][ki] = max(dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
res = 0
for fk,fv in cf.items():
res += dp[fv][cc.get(fk,0)]
print(res)
``` | output | 1 | 7,268 | 19 | 14,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | instruction | 0 | 7,269 | 19 | 14,538 |
Tags: dp
Correct Solution:
```
n,k= map(int,input().split(' '))
l= list(map(int,input().split(' ')))
f =list(map(int,input().split(' ')))
h=list(map(int,input().split(' ')))
d1=dict({(a,0) for a in f})
d2=dict({(a,0) for a in f})
for a in l:
if(a in d1):d1[a]+=1
for a in f:
d2[a]+=1
#print(d1,d2)
dp = [[0 for i in range(520*12)] for j in range(520)]
#print(len(dp), len(dp[0]))
for x in range(n+1):
for y in range(n*k+1):
for i in range(k+1):
dp[x+1][y+i] = max(dp[x+1][y+i],+dp[x][y]+(0 if i==0 else h[i-1]) )
ss=0
for i in d1:
#print(dp[d1[i]][d2[i]])
ss+=dp[d2[i]][d1[i]]
print(ss)
``` | output | 1 | 7,269 | 19 | 14,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | instruction | 0 | 7,270 | 19 | 14,540 |
Tags: dp
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('./input.txt')
# sys.stdin = f
def main():
n, k = RL()
cds = RLL()
fn = RLL()
sc = [0]+RLL()
rec = set(fn)
uses = 0
dic = defaultdict(int)
for i in cds:
if i in rec:
dic[i]+=1
uses+=1
dp = [[0]*(n*k+1) for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, n*k+1):
for l in range(k+1):
if l>j: break
val = sc[l]
dp[i][j] = max(dp[i][j], dp[i-1][j-l]+val)
res = 0
for i, v in Counter(fn).items():
res+=dp[v][dic[i]]
# for i in dp: print(i)
print(res)
if __name__ == "__main__":
main()
``` | output | 1 | 7,270 | 19 | 14,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | instruction | 0 | 7,271 | 19 | 14,542 |
Tags: dp
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def main():
n,k = map(int,input().split())
card = list(map(int,input().split()))
fav = list(map(int,input().split()))
joy = [0]+list(map(int,input().split()))
dp = [[0]*(n*k+1) for _ in range(n+1)]
for i in range(len(joy)):
dp[1][i] = joy[i]
for i in range(len(joy),n*k+1):
dp[1][i] = joy[-1]
for i in range(2,n+1):
for j in range(1,n*k+1):
for kk in range(min(k+1,j+1)):
dp[i][j] = max(dp[i][j],dp[i-1][j-kk]+dp[1][kk])
tot = [0]*(10**5+1)
for i in card:
tot[i] += 1
tot1 = [0]*(10**5+1)
for i in fav:
tot1[i] += 1
ans = 0
for i in range(10**5+1):
ans += dp[tot1[i]][tot[i]]
print(ans)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 7,271 | 19 | 14,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | instruction | 0 | 7,272 | 19 | 14,544 |
Tags: dp
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('./input.txt')
# sys.stdin = f
def main():
n, k = RL()
cds = RLL()
fn = RLL()
sc = [0]+RLL()
rec = set(fn)
uses = 0
dic = defaultdict(int)
for i in cds:
if i in rec:
dic[i]+=1
uses+=1
dp = [[0]*(uses+1) for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, uses+1):
for l in range(k+1):
if l>j: break
val = sc[l]
dp[i][j] = max(dp[i][j], dp[i-1][j-l]+val)
res = 0
for i, v in Counter(fn).items():
res+=dp[v][dic[i]]
# for i in dp: print(i)
print(res)
if __name__ == "__main__":
main()
``` | output | 1 | 7,272 | 19 | 14,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | instruction | 0 | 7,273 | 19 | 14,546 |
Tags: dp
Correct Solution:
```
from __future__ import print_function
from queue import Queue
import sys
import math
import os.path
# CONFIG
sys.setrecursionlimit(10**9)
# LOG
def log(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# INPUT
def ni():
return map(int, input().split())
def nio(offset):
return map(lambda x: int(x) + offset, input().split())
def nia():
return list(map(int, input().split()))
# CONVERT
def toString(aList, sep=" "):
return sep.join(str(x) for x in aList)
def mapInvertIndex(aList):
return {k: v for v, k in enumerate(aList)}
def countMap(arr):
m = {}
for x in arr:
m[x] = m.get(x,0) + 1
return m
def sortId(arr):
return sorted(range(arr), key=lambda k: arr[k])
# MAIN
n, k = ni()
c = nia()
f = nia()
h = [0]
h.extend(nia())
cc = countMap(c)
cf = countMap(f)
n1 = n+1
k1 = k+1
nk1 = n*k+1
dp = [[0]*nk1 for _ in range(n1)]
for ni in range(1,n1):
for ki in range(1,nk1):
mficount = min(k,ki) + 1
for kii in range(mficount):
# log(ni,ki, kii, dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
dp[ni][ki] = max(dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
# log(dp[ni])
# log(n,k)
# log("c", cc)
# log("f", cf)
# log("h", h)
# log(dp)
res = 0
for fk,fv in cf.items():
# log(fk, fv, cc.get(fk,0))
res += dp[fv][cc.get(fk,0)]
print(res)
``` | output | 1 | 7,273 | 19 | 14,547 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Submitted Solution:
```
from __future__ import print_function
from collections import Counter
from queue import Queue
import sys
import math
import os.path
# CONFIG
sys.setrecursionlimit(10**9)
# LOG
def log(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# INPUT
def ni():
return map(int, input().split())
def nio(offset):
return map(lambda x: int(x) + offset, input().split())
def nia():
return list(map(int, input().split()))
# CONVERT
def toString(aList, sep=" "):
return sep.join(str(x) for x in aList)
def mapInvertIndex(aList):
return {k: v for v, k in enumerate(aList)}
def sortId(arr):
return sorted(range(arr), key=lambda k: arr[k])
# MAIN
n, k = ni()
c = nia()
f = nia()
h = nia()
h.insert(0,0)
cc = Counter(c)
cf = Counter(f)
n1 = n+1
k1 = k+1
nk1 = n*k+1
dp = [[0]*nk1 for _ in range(n1)]
for ni in range(1,n1):
for ki in range(1,nk1):
mficount = min(k,ki) + 1
for kii in range(mficount):
# log(ni,ki, kii, dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
dp[ni][ki] = max(dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
# log(dp[ni])
# log(n,k)
# log("c", cc)
# log("f", cf)
# log("h", h)
# log(dp)
res = 0
for fk,fv in cf.items():
# log(fk, fv, cc.get(fk,0))
res += dp[fv][cc.get(fk,0)]
print(res)
``` | instruction | 0 | 7,274 | 19 | 14,548 |
Yes | output | 1 | 7,274 | 19 | 14,549 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n,k= map(int,input().split(' '))
l= list(map(int,input().split(' ')))
f =list(map(int,input().split(' ')))
h=list(map(int,input().split(' ')))
d1=dict({(a,0) for a in f})
d2=dict({(a,0) for a in f})
for a in l:
if(a in d1):d1[a]+=1
for a in f:
d2[a]+=1
#print(d1,d2)
dp = [[0 for i in range(520*12)] for j in range(520)]
#print(len(dp), len(dp[0]))
for x in range(n+1):
for y in range(n*k+1):
for i in range(k+1):
dp[x+1][y+i] = max(dp[x+1][y+i],+dp[x][y]+(0 if i==0 else h[i-1]) )
ss=0
for i in d1:
#print(dp[d1[i]][d2[i]])
ss+=dp[d2[i]][d1[i]]
print(ss)
``` | instruction | 0 | 7,275 | 19 | 14,550 |
Yes | output | 1 | 7,275 | 19 | 14,551 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Submitted Solution:
```
import math
from collections import defaultdict
def main():
n, k = map(int, input().split())
cards = list(map(int, input().split()))
fav = list(map(int, input().split()))
h = [0] + list(map(int, input().split()))
cards_cnt = defaultdict(int)
for val in cards:
cards_cnt[val] += 1
players_fav_cnt = defaultdict(int)
for val in fav:
players_fav_cnt[val] += 1
# dp[a][b] - a players, b favourite cards (in total)
dp = [[0 for _ in range(k*n+k+1)] for _ in range(n+1)]
for p in range(n):
for c in range(k*n+1):
for hand in range(k+1):
dp[p+1][c+hand] = max(dp[p+1][c+hand], dp[p][c] + h[hand])
res = 0
for f in players_fav_cnt:
res += dp[players_fav_cnt[f]][cards_cnt[f]]
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 7,276 | 19 | 14,552 |
Yes | output | 1 | 7,276 | 19 | 14,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Submitted Solution:
```
from __future__ import print_function
from collections import Counter
from queue import Queue
import sys
import math
import os.path
# CONFIG
sys.setrecursionlimit(10**9)
# LOG
def log(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# INPUT
def ni():
return map(int, input().split())
def nio(offset):
return map(lambda x: int(x) + offset, input().split())
def nia():
return list(map(int, input().split()))
# CONVERT
def toString(aList, sep=" "):
return sep.join(str(x) for x in aList)
def mapInvertIndex(aList):
return {k: v for v, k in enumerate(aList)}
def sortId(arr):
return sorted(range(arr), key=lambda k: arr[k])
# MAIN
n, k = ni()
c = nia()
f = nia()
h = nia()
h.insert(0,0)
cc = Counter(c)
cf = Counter(f)
n1 = n+1
k1 = k+1
nk1 = n*k+1
dp = [[0]*nk1 for _ in range(n1)]
for ni in range(1,n1):
for ki in range(1,nk1):
mficount = min(k,ki) + 1
for kii in range(mficount):
# log(ni,ki, kii, dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
dp[ni][ki] = max(dp[ni][ki], dp[ni-1][ki-kii] + h[kii])
# log(dp[ni])
# log(n,k)
# log("c", cc)
# log("f", cf)
# log("h", h)
# log(dp)
res = 0
for fk,fv in cf.items():
# log(fk, fv, cc.get(fk,0))
res += dp[fv][cc[fk]]
print(res)
``` | instruction | 0 | 7,277 | 19 | 14,554 |
Yes | output | 1 | 7,277 | 19 | 14,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Submitted Solution:
```
DEBUG = False
def dprint (*args, **kwargs):
pass
print (*args, **kwargs)
if DEBUG:
nk = "4 3"
c = "1 3 2 8 5 5 8 2 2 8 5 2"
f = "1 2 2 5"
h = "2 6 7"
else:
nk = input()
c = input()
f = input()
h = input()
n, k = map(int, nk.split())
c = list(map(int, c.split()))
f = list(map(int, f.split()))
#n = len(f)
#k = len(c) // n
h = list(map(int, h.split()))
znaki = set(c + f) # different card values in game
# find supply and demand
supply = {}
demand = {}
for z in znaki:
supply[z] = c.count(z)
demand[z] = f.count(z)
dprint("supply:", supply)
dprint("demand:", demand)
# build H-matrix
dm = max(demand.values())
sm = max(supply.values())
dprint (znaki, sm, dm)
'''
if n == 4:
print (21)
elif n == 3:
print (0)
else:
#map(int, c.split())
print (znaki, sm, dm)
ΠΠ²ΠΎΠ΄
500 10
2 1 1 2 2 ...
{1, 2} 2507 269
ΠΡΠ²Π΅Ρ
42588497
'''
def happy_1(num, pl):
if num == 0:
return 0
if pl == 0:
return 0
if pl == 1:
return h[min(num, k) - 1]
if num == 1:
return h[0]
max_hap = 0
for i in range(1, min(num, k) + 1):
hap = h[i - 1] + happy_1(num - i, pl - 1)
if hap > max_hap:
max_hap = hap
return max_hap
#dprint(happy_1(3, 1))
happy_matrix = []
for d in range(dm + 1):
happy_row = []
for s in range(min (sm, dm*k) + 1):
happy_row.append(happy_1(s, d))
# print(s, d, happy_1(s, d))
happy_matrix.append(happy_row)
dprint("happy_matrix:", happy_matrix)
# find H-functions
deficit_sum = 0
for z in znaki:
deficit = demand[z] * k - supply[z]
deficit_sum += deficit
dprint(z, deficit)
#print("deficit_sum", deficit_sum)
# reallocate cards
# calculate result
total_happy = 0
for z in znaki:
total_happy += happy_matrix[demand[z]][min(supply[z], demand[z] * k)]
print(total_happy)
dprint("total_happy:", total_happy)
``` | instruction | 0 | 7,278 | 19 | 14,556 |
No | output | 1 | 7,278 | 19 | 14,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Submitted Solution:
```
DEBUG = False
def dprint(*args, **kwargs):
if DEBUG:
print("#>",*args, **kwargs)
if DEBUG:
nk = "4 3"
c = "1 3 2 8 5 5 8 2 2 8 5 2"
f = "1 2 2 5"
h = "2 6 7"
else:
nk = input()
c = input()
f = input()
h = input()
n, k = map(int, nk.split())
c = list(map(int, c.split()))
f = list(map(int, f.split()))
# n = len(f)
# k = len(c) // n
h = list(map(int, h.split()))
znaki_s = set(c) # different card values in supply
znaki_d = set(f) # different card values in demand
znaki = set(c + f) # different card values in game
# find supply and demand
supply = {}
demand = {}
for z in znaki_s:
supply[z] = c.count(z)
for z in znaki_d:
demand[z] = f.count(z)
dprint("supply:", supply)
dprint("demand:", demand)
# build H-matrix
dm = max(demand.values())
sm = max(supply.values())
dprint(znaki, sm, dm)
if n == 4:
print (21)
elif n == 3:
print (0)
else:
print (n, k, znaki_s, f, h)
``` | instruction | 0 | 7,279 | 19 | 14,558 |
No | output | 1 | 7,279 | 19 | 14,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('./input.txt')
# sys.stdin = f
def main():
n, k = RL()
cds = RLL()
fn = RLL()
sc = [0]+RLL()
rec = set(fn)
uses = 0
dic = defaultdict(int)
for i in cds:
if i in rec:
dic[i]+=1
uses+=1
dp = [[0]*(uses+1) for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, uses+1):
if j>i*k: break
for l in range(k+1):
if l>j: break
val = sc[l]
dp[i][j] = max(dp[i][j], dp[i-1][j-l]+val)
res = 0
for i, v in Counter(fn).items():
res+=dp[v][dic[i]]
print(res)
if __name__ == "__main__":
main()
``` | instruction | 0 | 7,280 | 19 | 14,560 |
No | output | 1 | 7,280 | 19 | 14,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k β
n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ 10) β the number of players and the number of cards each player will get.
The second line contains k β
n integers c_1, c_2, ..., c_{k β
n} (1 β€ c_i β€ 10^5) β the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 β€ f_j β€ 10^5) β the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 β€ h_t β€ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t β [2..k].
Output
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Submitted Solution:
```
DEBUG = False
def dprint(*args, **kwargs):
if DEBUG:
print("#>",*args, **kwargs)
if DEBUG:
nk = "4 3"
c = "1 3 2 8 5 5 8 2 2 8 5 2"
f = "1 2 2 5"
h = "2 6 7"
else:
nk = input()
c = input()
f = input()
h = input()
n, k = map(int, nk.split())
c = list(map(int, c.split()))
f = list(map(int, f.split()))
# n = len(f)
# k = len(c) // n
h = list(map(int, h.split()))
znaki_s = set(c) # different card values in supply
znaki_d = set(f) # different card values in demand
znaki = set(c + f) # different card values in game
# find supply and demand
supply = {}
demand = {}
for z in znaki_s:
supply[z] = c.count(z)
for z in znaki_d:
demand[z] = f.count(z)
dprint("supply:", supply)
dprint("demand:", demand)
# build H-matrix
dm = max(demand.values())
sm = max(supply.values())
dprint(znaki, sm, dm)
if n == 4:
print (21)
elif n == 3:
print (0)
else:
print (demand, f, h)
``` | instruction | 0 | 7,281 | 19 | 14,562 |
No | output | 1 | 7,281 | 19 | 14,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice, Bob and Charlie are playing Card Game for Three, as below:
* At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged.
* The players take turns. Alice goes first.
* If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says `a`, Alice takes the next turn.)
* If the current player's deck is empty, the game ends and the current player wins the game.
There are 3^{N+M+K} possible patters of the three player's initial decks. Among these patterns, how many will lead to Alice's victory?
Since the answer can be large, print the count modulo 1\,000\,000\,007 (=10^9+7).
Constraints
* 1 \leq N \leq 3Γ10^5
* 1 \leq M \leq 3Γ10^5
* 1 \leq K \leq 3Γ10^5
Input
The input is given from Standard Input in the following format:
N M K
Output
Print the answer modulo 1\,000\,000\,007 (=10^9+7).
Examples
Input
1 1 1
Output
17
Input
4 2 2
Output
1227
Input
1000 1000 1000
Output
261790852
Submitted Solution:
```
mod=int(1E9+7)
JS=[1]
for i in range(1,4000):
JS.append(JS[-1]*i%mod)
Cs=lambda x,y:js(x)*inv(js(y))*inv(js(x-y))%mod
inv =lambda x:pow(x,mod-2,mod)
js=lambda x:JS[x]
#while True:
A,B,C=map(int,input().split())
A-=1;B+=1;C+=1;
ans=0
for x in range(1,B+1):
for y in range(1,C+1):
ans+=Cs(A+B-x+C-y,A)*Cs(B-x+C-y,B-x)*pow(3,x-1+y-1,mod)%mod
ans%=mod
print(ans)
``` | instruction | 0 | 7,418 | 19 | 14,836 |
No | output | 1 | 7,418 | 19 | 14,837 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice, Bob and Charlie are playing Card Game for Three, as below:
* At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged.
* The players take turns. Alice goes first.
* If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says `a`, Alice takes the next turn.)
* If the current player's deck is empty, the game ends and the current player wins the game.
There are 3^{N+M+K} possible patters of the three player's initial decks. Among these patterns, how many will lead to Alice's victory?
Since the answer can be large, print the count modulo 1\,000\,000\,007 (=10^9+7).
Constraints
* 1 \leq N \leq 3Γ10^5
* 1 \leq M \leq 3Γ10^5
* 1 \leq K \leq 3Γ10^5
Input
The input is given from Standard Input in the following format:
N M K
Output
Print the answer modulo 1\,000\,000\,007 (=10^9+7).
Examples
Input
1 1 1
Output
17
Input
4 2 2
Output
1227
Input
1000 1000 1000
Output
261790852
Submitted Solution:
```
#include <bits/stdc++.h>
using namespace std;
long long mod_pow(long long base, long long exp) {
if (exp == 0) return 1;
if (exp & 1)
return (mod_pow(base, exp - 1) * base) % 1000000007;
else
return mod_pow((base * base) % 1000000007, exp / 2);
}
long long fac[3 * 1000 + 1];
long long fac_inv[3 * 1000 + 1];
long long C(long long n, long long k) {
if (k < 0 || n < k) return 0;
long long num = fac[n];
long long den = (fac_inv[n - k] * fac_inv[k]) % 1000000007;
return (num * den) % 1000000007;
}
int main() {
fac[0] = 1;
for (long long n = 1; n <= 3 * 1000; n++)
fac[n] = (fac[n - 1] * n) % 1000000007;
fac_inv[3 * 1000] = mod_pow(fac[3 * 1000], 1000000007 - 2);
for (long long n = 3 * 1000 - 1; n >= 0; n--)
fac_inv[n] = (fac_inv[n + 1] * (n + 1)) % 1000000007;
long long a, b, c;
cin >> a >> b >> c;
a++;
if (!(b > c)) {
b = b ^ c;
c = b ^ c;
b = b ^ c;
}
long long ans = 0;
long long sum = 1;
long long pull = 0;
for (long long n = a; n <= a + b + c; n++) {
long long sub = 0;
sub = (sub + sum - pull) % 1000000007;
sub = (sub * C(n - 2, a - 2)) % 1000000007;
sub = (sub * mod_pow(3, a + b + c - n)) % 1000000007;
ans = (ans + sub) % 1000000007;
sum = (2 * sum - C(n - a, c)) % 1000000007;
pull = (2 * pull + C(n - a, n - a - b)) % 1000000007;
}
cout << (ans + 1000000007) % 1000000007 << endl;
return 0;
}
``` | instruction | 0 | 7,419 | 19 | 14,838 |
No | output | 1 | 7,419 | 19 | 14,839 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice, Bob and Charlie are playing Card Game for Three, as below:
* At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter `a`, `b` or `c` written on it. The orders of the cards in the decks cannot be rearranged.
* The players take turns. Alice goes first.
* If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says `a`, Alice takes the next turn.)
* If the current player's deck is empty, the game ends and the current player wins the game.
There are 3^{N+M+K} possible patters of the three player's initial decks. Among these patterns, how many will lead to Alice's victory?
Since the answer can be large, print the count modulo 1\,000\,000\,007 (=10^9+7).
Constraints
* 1 \leq N \leq 3Γ10^5
* 1 \leq M \leq 3Γ10^5
* 1 \leq K \leq 3Γ10^5
Input
The input is given from Standard Input in the following format:
N M K
Output
Print the answer modulo 1\,000\,000\,007 (=10^9+7).
Examples
Input
1 1 1
Output
17
Input
4 2 2
Output
1227
Input
1000 1000 1000
Output
261790852
Submitted Solution:
```
mod=int(1E9+7)
JS=[1]
for i in range(1,5000):
JS.append(JS[-1]*i%mod)
Cs=lambda x,y:js(x)*inv(js(y))*inv(js(x-y))%mod
inv =lambda x:pow(x,mod-2,mod)
js=lambda x:JS[x]
#while True:
A,B,C=map(int,input().split())
A-=1;B+=1;C+=1;
ans=0
for x in range(1,B+1):
for y in range(1,C+1):
ans+=Cs(A+B-x+C-y,A)*Cs(B-x+C-y,B-x)*pow(3,x-1+y-1,mod)%mod
ans%=mod
print(ans)
``` | instruction | 0 | 7,420 | 19 | 14,840 |
No | output | 1 | 7,420 | 19 | 14,841 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | instruction | 0 | 7,565 | 19 | 15,130 |
Tags: implementation
Correct Solution:
```
# Blackjack
def cards(n):
diff = n - 10
if diff == 10:
return 15
if diff > 11 or diff == 0:
return 0
if n < 10:
return 0
else:
return 4
n = int(input())
print(cards(n))
``` | output | 1 | 7,565 | 19 | 15,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | instruction | 0 | 7,566 | 19 | 15,132 |
Tags: implementation
Correct Solution:
```
n = int(input())
if 1 <= n-10 <= 9 or n-10 == 11:
print("4")
elif n-10 == 10:
print("15")
else:
print("0")
``` | output | 1 | 7,566 | 19 | 15,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | instruction | 0 | 7,567 | 19 | 15,134 |
Tags: implementation
Correct Solution:
```
n = int(input())
if n <= 10 or n > 21:
print(0)
else:
if n == 11 or n == 21:
print(4)
elif n - 10 < 10:
print(4)
else:
print(15)
``` | output | 1 | 7,567 | 19 | 15,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | instruction | 0 | 7,568 | 19 | 15,136 |
Tags: implementation
Correct Solution:
```
n=int(input())
n=n-10
if(n>=1 and n<=9):
print(4)
elif(n==10):
print(15)
elif(n==11):
print(4)
else:
print(0)
``` | output | 1 | 7,568 | 19 | 15,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | instruction | 0 | 7,569 | 19 | 15,138 |
Tags: implementation
Correct Solution:
```
n=int(input())
if 11<=n<=19:
print(4)
elif n==20:
print(15)
elif n==21:
print(4)
else:
print(0)
``` | output | 1 | 7,569 | 19 | 15,139 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | instruction | 0 | 7,570 | 19 | 15,140 |
Tags: implementation
Correct Solution:
```
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11, 10] * 4
a = a[:-1]
def solve(n):
print(a.count(n - 10))
n, = map(int, input().split())
solve(n)
``` | output | 1 | 7,570 | 19 | 15,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | instruction | 0 | 7,571 | 19 | 15,142 |
Tags: implementation
Correct Solution:
```
n=int(input())
x=n-10
if(x<=0):
print(0)
else:
if(x>11):
print(0)
elif(x==10):
print(15)
else:
print(4)
``` | output | 1 | 7,571 | 19 | 15,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | instruction | 0 | 7,572 | 19 | 15,144 |
Tags: implementation
Correct Solution:
```
# import sys
# sys.stdin=open("input.in",'r')
# sys.stdout=open("out.out",'w')
n=int(input())-10
if n<=0:
print(0)
elif n==10:
print(15)
elif n<12:
print(4)
else:
print(0)
``` | output | 1 | 7,572 | 19 | 15,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
Submitted Solution:
```
x = int(input())-10
if 1<=x<=9 or x == 11:
print(4)
elif x==10 or x==20:
print(15)
else:
print(0)
``` | instruction | 0 | 7,573 | 19 | 15,146 |
Yes | output | 1 | 7,573 | 19 | 15,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
Submitted Solution:
```
""" *** Author--Saket Saumya ***
IIITM
"""
import math
from sys import stdin
def si():
return str(input())
def ii():
return int(input())
def mi():
return map(int, input().split())
def li():
return list(mi())
n=ii()
s=n-10
if s==0 or s>=12 or s<0:
print('0')
if(s==1) or s==2 or s==3 or s==4 or s==5 or s==6 or s==7 or s==8 or s==9:
print('4')
if(s==10):
print('15')
if s==11:
print('4')
``` | instruction | 0 | 7,574 | 19 | 15,148 |
Yes | output | 1 | 7,574 | 19 | 15,149 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
Submitted Solution:
```
n = int(input())
if (n >= 0 and n <= 10) or n >= 22:
print(0)
elif (n >= 11 and n < 20) or n == 21:
print(4)
elif n == 20:
print(15)
``` | instruction | 0 | 7,575 | 19 | 15,150 |
Yes | output | 1 | 7,575 | 19 | 15,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
Submitted Solution:
```
n=int(input())
if (n-10)<=0 or n>=22:
print(0)
elif 1<=(n-10)<=11 and n!=20:
print(4)
elif n==20:
print(15)
``` | instruction | 0 | 7,576 | 19 | 15,152 |
Yes | output | 1 | 7,576 | 19 | 15,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
Submitted Solution:
```
n=int(input())
if n==10:
print('0')
elif n==20:
print('15')
else:
print('4')
``` | instruction | 0 | 7,577 | 19 | 15,154 |
No | output | 1 | 7,577 | 19 | 15,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
Submitted Solution:
```
n=int(input())
if(n<=10):
print('0')
else:
t=n-10
if(t==10):
print('15')
else:
print('4')
``` | instruction | 0 | 7,578 | 19 | 15,156 |
No | output | 1 | 7,578 | 19 | 15,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
Submitted Solution:
```
def ans(n):
if(n==0 or n>11):
return 0
elif(1<=n<10) or (n==11):
return 4
else:
return 15
n=int(input())
n-=10
print(ans(n))
``` | instruction | 0 | 7,579 | 19 | 15,158 |
No | output | 1 | 7,579 | 19 | 15,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.
Input
The only line contains n (1 β€ n β€ 25) β the required sum of points.
Output
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Examples
Input
12
Output
4
Input
20
Output
15
Input
10
Output
0
Note
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points.
Submitted Solution:
```
n = int(input())
if n == 20:
print(15)
elif 10 < n < 22:
print(0)
else:
print(4)
``` | instruction | 0 | 7,580 | 19 | 15,160 |
No | output | 1 | 7,580 | 19 | 15,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 β€ k β€ 10^{18}) β the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 β€ n β€ 2000) β the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used. | instruction | 0 | 7,767 | 19 | 15,534 |
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
a = []
if n % 2 == 1:
print(-1)
continue
if n <= 4000:
print(n // 2)
print('1 ' * (n // 2))
continue
while n > 0:
a.append(1)
n -= 2
s = 2
while n > s * 2:
a.append(0)
s *= 2
n -= s
if len(a) <= 2000:
print(len(a))
print(*a, end=' ')
else:
print(-1)
``` | output | 1 | 7,767 | 19 | 15,535 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 β€ k β€ 10^{18}) β the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 β€ n β€ 2000) β the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used. | instruction | 0 | 7,768 | 19 | 15,536 |
Tags: brute force, constructive algorithms, greedy, math, probabilities
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 bisect import bisect_left as bsl
powers=[2]
for s in range(60):
powers.append(powers[-1]*2)
newy=[powers[0]]
for s in range(1,len(powers)):
newy.append(newy[-1]+powers[s])
if newy[-1]>=10**18:
break
for j in range(int(input())):
k=int(input())
if k%2==1:
print(-1)
else:
binrep=k-2
#see if we can construct k-2 using newy
ans=[1]
while binrep>0:
ind=min(bsl(newy,binrep),len(newy)-1)
if newy[ind]>binrep:
ind-=1
for i in range(ind):
ans.append(0)
ans.append(1)
binrep-=newy[ind]
print(len(ans))
print(*ans)
``` | output | 1 | 7,768 | 19 | 15,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 β€ k β€ 10^{18}) β the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 β€ n β€ 2000) β the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used. | instruction | 0 | 7,769 | 19 | 15,538 |
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
from sys import stdin
input = stdin.readline
for _ in range(int(input())):
n = int(input())
s = ''
if n % 2:
print(-1)
continue
n //= 2
a = bin(n)[2:]
n = len(a)
for x in range(n - 1, 0, -1):
if a[n - 1 - x] == '0':
continue
s += '1 ' + '0 ' * (x - 1) + '1 '
if a[n - 1] == '1':
s += '1 '
print(len(s) // 2)
print(s)
``` | output | 1 | 7,769 | 19 | 15,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 β€ k β€ 10^{18}) β the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 β€ n β€ 2000) β the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used. | instruction | 0 | 7,770 | 19 | 15,540 |
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
def read_int():
return int(input())
def read_ints():
return map(int, input().split(' '))
t = read_int()
a = [2]
while a[-1] < 1e18:
a.append(a[-1] * 2 + 2)
for case_num in range(t):
n = read_int()
if n % 2 == 1:
print(-1)
continue
ans = []
pos = len(a) - 1
while n > 0:
while a[pos] > n:
pos -= 1
n -= a[pos]
ans += [1] + ([0] * pos)
print(len(ans))
print(' '.join(map(str, ans)))
``` | output | 1 | 7,770 | 19 | 15,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 β€ k β€ 10^{18}) β the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 β€ n β€ 2000) β the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used. | instruction | 0 | 7,771 | 19 | 15,542 |
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
t = int(input())
al = [2]
for i in range(100):
al.append(al[-1] * 2 + 2)
#print(al)
for q in range(t):
k = int(input())
if k % 2 == 1:
print(-1)
else:
mas = []
while k > 0:
y = 0
while al[y] <= k:
y += 1
y -= 1
mas.append(y)
k -= al[y]
z = 0
for i in mas:
z += i + 1
print(z)
for i in mas:
print(1, end = ' ')
for j in range(i):
print(0, end = ' ')
print()
``` | output | 1 | 7,771 | 19 | 15,543 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.