text stringlengths 1.02k 43.5k | conversation_id int64 853 107k | embedding list | cluster int64 24 24 |
|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Tags: binary search, constructive algorithms, data structures, interactive
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq,bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default, func):
"""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 binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,t=map(int,input().split())
ind=defaultdict(int)
se=set()
e=[0]*n
s=SegmentTree(e)
for i in range(t):
k=int(input())
st=0
end=n-1
ans=n-1
while(st<=end):
mid=(st+end)//2
if mid in se:
inp=ind[mid]-s.query(0,mid)
else:
print("? 1",mid+1,flush=True)
inp=int(input())
inp=mid+1-inp
se.add(mid)
ind[mid]=inp+s.query(0,mid)
if inp>=k:
ans=mid
end=mid-1
else:
st=mid+1
s.__setitem__(ans,1)
print("!",ans+1,flush=True)
```
| 49,909 | [
0.32568359375,
0.041107177734375,
0.047576904296875,
0.10833740234375,
-0.449951171875,
-0.64794921875,
-0.5693359375,
0.214111328125,
-0.08380126953125,
0.67529296875,
0.943359375,
-0.055908203125,
0.01253509521484375,
-0.52001953125,
-0.66455078125,
-0.0080413818359375,
-0.16186523... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Tags: binary search, constructive algorithms, data structures, interactive
Correct Solution:
```
import os
import sys
from collections import defaultdict,deque
from heapq import heappush,heappop
from io import BytesIO, IOBase
nmbr = lambda: int(input())
lst = lambda: list(map(int, input().split()))
def main():
def update(ind, diff):
# ind += 1
while ind <= n:
fw[ind] += diff
ind = ind + (ind & -ind)
def sumtill(pos):
# pos += 1
s = 0
while pos > 0:
s += fw[pos]
pos = pos - (pos & -pos)
return s
n, tt = lst()
dp = [-1] * (1 + n)
fw = [0] * (2 + n)
for ttt in range(tt):
k = nmbr()
# print(dp)
# print([sumtill(i) for i in range(n+1)])
l, r = 1, n
while l <= r:
mid = (l + r) >> 1
extra = sumtill(mid)
if dp[mid] == -1:
print('?', 1, mid);
sys.stdout.flush()
sm = nmbr()
dp[mid] = sm - extra
sm = dp[mid] + extra
if mid - sm < k:
l = mid + 1
else:
r = mid - 1
# print(dp)
print('!', l);
sys.stdout.flush()
update(l, 1)
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__":
for t in range(1):main()#int(input())):
```
| 49,910 | [
0.32568359375,
0.041107177734375,
0.047576904296875,
0.10833740234375,
-0.449951171875,
-0.64794921875,
-0.5693359375,
0.214111328125,
-0.08380126953125,
0.67529296875,
0.943359375,
-0.055908203125,
0.01253509521484375,
-0.52001953125,
-0.66455078125,
-0.0080413818359375,
-0.16186523... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Tags: binary search, constructive algorithms, data structures, interactive
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
from heapq import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M = 10**9 + 7
EPS = 1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def Get(l,r):
if(info[r] != -1): return info[r]
print('?',l,r,flush=True)
return r - Int()
n,t = value()
info = [-1]*(n+1)
for _ in range(t):
k = Int()
l = 1
r = n
# for i in range(1,n+1):
# if(info[i] == -1): continue
# if(info[i] < k): l = max(i + 1,l)
# if(info[i] >= k): r = min(i,r)
while(l<r):
m = l + (r-l)//2
left_zero = Get(1,m)
info[m] = left_zero
if(left_zero == -1): exit()
if(left_zero >= k):
ans = m
r = m
else:
l = m + 1
ans = l
for i in range(ans,n+1):
if(info[i] != -1): info[i] -= 1
print('!',ans,flush=True)
```
| 49,911 | [
0.32568359375,
0.041107177734375,
0.047576904296875,
0.10833740234375,
-0.449951171875,
-0.64794921875,
-0.5693359375,
0.214111328125,
-0.08380126953125,
0.67529296875,
0.943359375,
-0.055908203125,
0.01253509521484375,
-0.52001953125,
-0.66455078125,
-0.0080413818359375,
-0.16186523... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Tags: binary search, constructive algorithms, data structures, interactive
Correct Solution:
```
# 62 ms 6600 KB
import sys
n,t=map(int,input().split())
d={}
for _ in range(t):
k=int(input())
l=1; r=n;
while l<r:
m=(l+r)>>1
if (l,m) not in d:
print("?",l,m)
sys.stdout.flush()
s=int(input())
d[(l,m)]=s
s=d[(l,m)]
if m-l+1-s>=k: r=m
else: k-=(m-l+1-s); l=m+1
if (l,r) in d: d[(l,r)]+=1
print("!",r)
```
| 49,912 | [
0.32568359375,
0.041107177734375,
0.047576904296875,
0.10833740234375,
-0.449951171875,
-0.64794921875,
-0.5693359375,
0.214111328125,
-0.08380126953125,
0.67529296875,
0.943359375,
-0.055908203125,
0.01253509521484375,
-0.52001953125,
-0.66455078125,
-0.0080413818359375,
-0.16186523... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Tags: binary search, constructive algorithms, data structures, interactive
Correct Solution:
```
n, t = map(int, input().split())
mem = {}
for _ in range(t):
k = int(input())
left, right = 1, n
while right > left:
mid = (left + right) // 2
if (left, mid) not in mem:
print(f'? {left} {mid}')
mem[(left, mid)] = mid - left + 1 - int(input())
num_of_zeros = mem[(left, mid)]
if num_of_zeros < k:
left = mid + 1
k -= num_of_zeros
else:
right = mid
if (left, right) in mem:
mem[(left, right)] -= 1
print(f'! {left}')
```
| 49,913 | [
0.32568359375,
0.041107177734375,
0.047576904296875,
0.10833740234375,
-0.449951171875,
-0.64794921875,
-0.5693359375,
0.214111328125,
-0.08380126953125,
0.67529296875,
0.943359375,
-0.055908203125,
0.01253509521484375,
-0.52001953125,
-0.66455078125,
-0.0080413818359375,
-0.16186523... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Tags: binary search, constructive algorithms, data structures, interactive
Correct Solution:
```
import sys
n,t=map(int,input().split())
mem={}
for _ in range(t):
k=int(input())
l,r=1,n
while l<r:
mid=(l+r)//2
if (l,mid) not in mem:
print('?',l,mid)
sys.stdout.flush()
mem[(l,mid)]=mid-l+1-int(input())
val=mem[(l,mid)]
if k<=val:
r=mid
else:
k-=val
l=mid+1
if (l,r) in mem:
mem[(l,r)]-=1
print('!',l)
```
| 49,914 | [
0.32568359375,
0.041107177734375,
0.047576904296875,
0.10833740234375,
-0.449951171875,
-0.64794921875,
-0.5693359375,
0.214111328125,
-0.08380126953125,
0.67529296875,
0.943359375,
-0.055908203125,
0.01253509521484375,
-0.52001953125,
-0.66455078125,
-0.0080413818359375,
-0.16186523... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Tags: binary search, constructive algorithms, data structures, interactive
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
from bisect import bisect_left
def query(l,r):
print(f"? {l} {r}")
sys.stdout.flush()
return int(input())
def found(i):
print(f"! {i}")
sys.stdout.flush()
n,t = map(int,input().split())
k = int(input())
changed = [0]*(n+1)
blocks = [0]*(n//16+1) # blocks of size 16 # of zeros
for i in range(1,n//16+1):
blocks[i] = 16 - query((i-1)*16+1, i*16)
for j in range(t):
num0 = blocks[0]
idx = 0
while idx + 1 < len(blocks) and num0 + blocks[idx+1] < k:
idx += 1
num0 += blocks[idx]
pos = 16*(idx)
diff0 = k - num0
num0 = 0
for i in range(3,-1,-1):
if pos + (1 << i) > n:
continue
new0 = (1<<i) - query(pos+1,pos+(1<<i))
if num0 + new0 < diff0:
pos += (1<<i)
num0 += new0
found(pos+1)
if idx+1 < len(blocks):
blocks[idx+1] -= 1
if j != t-1:
k = int(input())
```
| 49,915 | [
0.32568359375,
0.041107177734375,
0.047576904296875,
0.10833740234375,
-0.449951171875,
-0.64794921875,
-0.5693359375,
0.214111328125,
-0.08380126953125,
0.67529296875,
0.943359375,
-0.055908203125,
0.01253509521484375,
-0.52001953125,
-0.66455078125,
-0.0080413818359375,
-0.16186523... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Submitted Solution:
```
import sys
from collections import defaultdict
n,t=map(int,input().split())
mem={}
# def dec(pos,l,r):
# mem[(l,r)]-=1
# if l!=r:
# mid=(l+r)//2
# if pos<=mid:
# dec(pos,l,mid)
# else:
# dec(pos,mid+1,r)
for _ in range(t):
k=int(input())
l,r=1,n
while l<r:
# mem[(l,r)]-=1
mid=(l+r)//2
if (l,mid) not in mem:
print('?',l,mid)
sys.stdout.flush()
mem[(l,mid)]=mid-l+1-int(input())
val=mem[(l,mid)]
if k<=val:
r=mid
else:
k-=val
l=mid+1
if (l,r) in mem:
mem[(l,r)]-=1
# print(mem)
print('!',l)
# dec(l,1,n)
```
Yes
| 49,916 | [
0.427490234375,
0.112548828125,
0.0008320808410644531,
0.058563232421875,
-0.541015625,
-0.515625,
-0.529296875,
0.2032470703125,
-0.11993408203125,
0.70068359375,
0.85205078125,
-0.060882568359375,
-0.0024261474609375,
-0.52978515625,
-0.67431640625,
-0.08074951171875,
-0.2445068359... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
def ask(mid,b,lo):
z=b[(lo,mid)]
if z:
return z
else:
print("?",lo,mid,flush=1)
x=(mid-lo+1)-int(input())
b[(lo,mid)]=x
return x
def solve(n,b):
k=int(input())
lo,hi,ans,a=1,n,1,[]
while lo<=hi:
mid=(lo+hi)//2
z=ask(mid,b,lo)
a.append((lo,mid))
if z>=k:
hi=mid-1
if z==k:
ans=mid
else:
k-=z
lo=mid+1
for i in a:
if i[0]<=ans and ans<=i[1]:
b[i]-=1
print("!",ans,flush=1)
def main():
n,t=map(int,input().split())
b=Counter()
for _ in range(t):
solve(n,b)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
Yes
| 49,917 | [
0.427490234375,
0.112548828125,
0.0008320808410644531,
0.058563232421875,
-0.541015625,
-0.515625,
-0.529296875,
0.2032470703125,
-0.11993408203125,
0.70068359375,
0.85205078125,
-0.060882568359375,
-0.0024261474609375,
-0.52978515625,
-0.67431640625,
-0.08074951171875,
-0.2445068359... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Submitted Solution:
```
import sys
'''
*data, = sys.stdin.read().split("\n")[::-1]
def input():
return data.pop()
'''
def fprint(*args, **kwargs):
print(*args, **kwargs, flush=True)
def eprint(*args, **kwargs):
print(*args, **kwargs, file=sys.stderr)
query_counter = 0
def query(l, r):
global query_counter
query_counter += 1
fprint("? {} {}".format(l, r))
assert query_counter < 6e4
return int(input())
def binsearch(l, r, rem):
oriel = l
while r - l > 1:
# print("r", l, r)
mid = (l + r) // 2
eprint("cur", l, mid, rem)
query_res = mid - oriel - query(oriel + 1, mid)
if query_res >= rem:
r = mid
else:
l = mid
return l
n, t = map(int, input().split())
q = int(input())
nseg16 = (n + 15) // 16 + 1
seg16 = [0] * nseg16
segsize = 16
def get_right(i):
min(n, (i + 1) * 16)
for i in range(nseg16 - 1):
right = min(n, (i + 1) * 16)
if i > 0:
assert get_right(i - 1) != right
seg16[i + 1] = right - query(1, right)
assert sorted(seg16) == seg16
def solve(q):
assert q != 0
l = 0
r = nseg16
while l != r:
mid = (l + r) // 2
if seg16[mid] < q:
l = mid + 1
else:
r = mid
assert l != 0
res = binsearch((l - 1) * 16, min(l * 16, n), rem=q - seg16[l - 1])
for j in range(l, nseg16):
seg16[j] -= 1
print("! {}".format(res + 1), flush=True)
solve(q)
for _ in range(t - 1):
q = int(input())
solve(q)
```
Yes
| 49,918 | [
0.427490234375,
0.112548828125,
0.0008320808410644531,
0.058563232421875,
-0.541015625,
-0.515625,
-0.529296875,
0.2032470703125,
-0.11993408203125,
0.70068359375,
0.85205078125,
-0.060882568359375,
-0.0024261474609375,
-0.52978515625,
-0.67431640625,
-0.08074951171875,
-0.2445068359... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Submitted Solution:
```
import bisect
n,t=map(int,input().split())
vis=[None]*(n+1)
arr=[]
for i in range(t):
k=int(input())
start=0
end=n-1
pos=-1
while start<=end:
mid=(start+end)//2
if vis[mid+1]==None:
print("?",1,mid+1)
x=int(input())
vis[mid+1]=x
vis[mid+1]=vis[mid+1]-bisect.bisect_right(arr,mid+1)
else:
x=vis[mid+1]+bisect.bisect_right(arr,mid+1)
if mid+1-x==k:
pos=mid+1
end=mid-1
elif mid+1-x<k:
start=mid+1
elif mid+1-x>k:
end=mid-1
bisect.insort(arr,pos)
print("!",pos)
# print(vis)
# print(arr)
exit()
```
Yes
| 49,919 | [
0.427490234375,
0.112548828125,
0.0008320808410644531,
0.058563232421875,
-0.541015625,
-0.515625,
-0.529296875,
0.2032470703125,
-0.11993408203125,
0.70068359375,
0.85205078125,
-0.060882568359375,
-0.0024261474609375,
-0.52978515625,
-0.67431640625,
-0.08074951171875,
-0.2445068359... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, t = map(int, input().split())
class BIT:
def __init__(self, n):
self.n = n
self.data = [0] * (n + 1)
self.el = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
def get(self, i, j = None):
if j is None:
return self.el[i]
return self.sum(j) - self.sum(i)
def lowerbound(self, s):
x = 0
y = 0
for i in range(self.n.bit_length(), -1, -1):
k = x + (1 << i)
if k <= self.n and (y + self.data[k] < s):
y += self.data[k]
x += 1 << i
return x + 1
fwk = BIT(n + 1)
fwk.add(1, -1)
for _ in range(t):
k = int(input())
ok = n
ng = 0
while ok - ng > 1:
m = (ok + ng) // 2
q = 0
#print(fwk.sum(m), m)
if fwk.sum(m) == -1:
print("?", 1, m)
sys.stdout.flush()
q = int(input())
else: q = fwk.sum(m)
if k <= m - q: ok = m
else: ng = m
val = fwk.sum(m)
fwk.add(m, q - val)
fwk.add(m + 1, -(q - val))
print("!", ok)
sys.stdout.flush()
fwk.add(ok, 1)
fwk.add(ok + 1, -1)
```
No
| 49,920 | [
0.427490234375,
0.112548828125,
0.0008320808410644531,
0.058563232421875,
-0.541015625,
-0.515625,
-0.529296875,
0.2032470703125,
-0.11993408203125,
0.70068359375,
0.85205078125,
-0.060882568359375,
-0.0024261474609375,
-0.52978515625,
-0.67431640625,
-0.08074951171875,
-0.2445068359... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#####################################
n,t=map(int,input().split())
c=-1
ans=-1
for _ in range(t):
k=int(input())
if c==-1:
l=1
h=n
elif c<k:
l=1
h=c-1
else:
l=mid+1
h=n
while l<=h:
mid=(l+h)//2
print('?',1,mid,flush=True)
a=int(input())
if mid-a<k:
l=mid+1
else:
if l==h==mid:
break
h=mid
ans=mid
c=k
print('!',mid,flush=True)
```
No
| 49,921 | [
0.427490234375,
0.112548828125,
0.0008320808410644531,
0.058563232421875,
-0.541015625,
-0.515625,
-0.529296875,
0.2032470703125,
-0.11993408203125,
0.70068359375,
0.85205078125,
-0.060882568359375,
-0.0024261474609375,
-0.52978515625,
-0.67431640625,
-0.08074951171875,
-0.2445068359... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Submitted Solution:
```
import sys
'''
*data, = sys.stdin.read().split("\n")[::-1]
def input():
return data.pop()
'''
def fprint(*args, **kwargs):
print(*args, **kwargs, flush=True)
def eprint(*args, **kwargs):
print(*args, **kwargs, file=sys.stderr)
def query(l, r):
fprint("? {} {}".format(l, r))
return int(input())
def binsearch(l, r, rem):
while r - l > 1:
# eprint("cur", l, r, rem)
# print("r", l, r)
mid = (l + r) // 2
query_res = mid - l - query(l + 1, mid)
if query_res >= rem:
r = mid
else:
l = mid
rem -= query_res
return l
n, t = map(int, input().split())
queries = []
for _ in range(t):
queries.append(int(input()))
fprint("! 1")
sys.exit(0)
nseg16 = (n + 15) // 16
seg16 = [0] * (nseg16 + 1)
for i in range(nseg16):
segsize = 16
if i == nseg16 - 1:
segsize = n - i * 16
seg16[i + 1] = seg16[i] + segsize - query(i * 16 + 1, (i + 1) * 16)
for q in queries:
l = 0
r = nseg16 + 1
while l != r:
mid = (l + r) // 2
if seg16[mid] < q:
l = mid + 1
else:
r = mid
res = binsearch((l - 1) * 16, min(l * 16, n), rem=seg16[l] - seg16[l - 1])
print("! {}".format(res + 1), flush=True)
for i in range(l, nseg16 + 1):
seg16[i] += 1
'''
check = int(input())
if check == -1:
break
'''
```
No
| 49,922 | [
0.427490234375,
0.112548828125,
0.0008320808410644531,
0.058563232421875,
-0.541015625,
-0.515625,
-0.529296875,
0.2032470703125,
-0.11993408203125,
0.70068359375,
0.85205078125,
-0.060882568359375,
-0.0024261474609375,
-0.52978515625,
-0.67431640625,
-0.08074951171875,
-0.2445068359... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4.
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the k-th zero from the left t times.
Polycarp can make no more than 6 ⋅ 10^4 requests totally of the following type:
* ? l r — find out the sum of all elements in positions from l to r (1 ≤ l ≤ r ≤ n) inclusive.
To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the k-th zero was x, then after Polycarp guesses this position, the x-th element of the array will be replaced from 0 to 1.
Help Polycarp win the game.
Interaction
First, your program must read two integers n and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ t ≤ min(n, 10^4)).
Then t lines follow, each of which contains one integer k (1 ≤ k ≤ n). It is guaranteed that at the moment of the request the array contains at least k zeros. In order to get the next value of k, you must output the answer for the previous value of k.
After that, you can make no more than 6 ⋅ 10^4 requests in total.
Use the following format to output the answer (it is not a request, it doesn't count in 6 ⋅ 10^4):
* ! x — position of the k-th zero.
Positions in the array are numbered from left to right from 1 to n inclusive.
After printing t answers, your program should exit immediately.
In this task, the interactor is not adaptive. This means that within the same test, the hidden array and the queries do not change.
In case of an incorrect query, -1 will be displayed. When this value is received, your program must immediately exit normally (for example, by calling exit(0)), otherwise, the testing system may issue an arbitrary verdict.
If the number of requests is exceeded, the verdict wrong answer will be displayed.
Your solution may get the verdict Idleness limit exceeded if you don't print anything or forget to flush the output buffer.
To flush the output buffer, you need to do the following immediately after the query output and the end-of-line character:
* fflush(stdout) or cout.flush() in C ++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
Use the following format for hacks:
On the first line print the string s (1 ≤ |s| ≤ 2 ⋅ 10^5), consisting of zeros and ones, and an integer t (1 ≤ t ≤ min(|s|, 10^4)) — hidden array and number of requests, respectively. In the next t lines output the number k (1 ≤ k ≤ |s|).
The hacked solution will not have direct access to the hidden array.
Example
Input
6 2
2
2
1
1
0
1
0
Output
? 4 6
? 1 1
? 1 2
? 5 5
! 5
? 2 2
! 2
Note
In the first test, the array [1, 0, 1, 1, 0, 1] is hidden. After answering the query k=2, the array changed to [1, 0, 1, 1, 1, 1].
Submitted Solution:
```
"""
Author - Satwik Tiwari .
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt,log2
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def modInverse(b):
g = gcd(b, mod)
if (g != 1):
# print("Inverse doesn't exist")
return -1
else:
# If b and m are relatively prime,
# then modulo inverse is b^(m-2) mode m
return pow(b, mod - 2, mod)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
# from random import randint
from sys import stdout
def ask(l,r):
print('?',l + 1,r + 1)
stdout.flush()
temp = int(inp())
len = r - l + 1
return len - temp #return number of zeroes in l to r
def ans(i):
print('!',i + 1)
stdout.flush()
def solve(case):
n,t = sep()
pre = []
cnt = 0
for i in range(t):
assert (cnt < 60000)
k = int(inp())
if(i == 0):
# every index consist of 32 range.
for j in range(0,n,32):
l = j
r = min(j + 32 - 1, n-1)
assert (cnt < 60000)
pre.append(ask(l,r))
cnt += 1
for i in range(1,len(pre)): #todo update pre after every query
pre[i] += pre[i-1]
ind = bl(pre,k)
lo = ind*32
hi = min(lo + 31,n-1)
# print(pre,ind,lo,hi,k)
while(lo <= hi):
if(lo == hi):
ans(lo)
break
if(hi == lo + 1):
assert (cnt < 60000)
temp = ask(lo,lo); cnt += 1
if(temp == k):
ans(lo)
else: ans(hi)
break
mid = (lo + hi)//2
assert (cnt < 60000)
currzero = ask(lo,mid); cnt+=1
if(currzero >= k):
hi = mid
else:
k -= currzero
lo = mid+1
for j in range(ind,len(pre)):
pre[j]-=1
assert (cnt <= 60000)
# temp = [randint(0,1) for i in range(10)]
# f = True
# while(f):
# testcase(1)
# temp = [randint(0,1) for i in range(10)]
testcase(1)
# testcase(int(inp()))
```
No
| 49,923 | [
0.427490234375,
0.112548828125,
0.0008320808410644531,
0.058563232421875,
-0.541015625,
-0.515625,
-0.529296875,
0.2032470703125,
-0.11993408203125,
0.70068359375,
0.85205078125,
-0.060882568359375,
-0.0024261474609375,
-0.52978515625,
-0.67431640625,
-0.08074951171875,
-0.2445068359... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Tags: implementation
Correct Solution:
```
r = lambda: int(input())
ra = lambda: [*map(int, input().split())]
a = []
t, q, mq, s = 0, 0, 0, 0
n = r()
for i in range(n):
a.append(ra())
for i in range(n):
if i==0:
q = a[i][1]
t = a[i][0]
else:
s = a[i][0] - t
q-=s
if q<0:
q = 0
q+=a[i][1]
if q>mq:
mq = q
t = a[i][0]
t = a[i][0]+q
print(t, mq)
```
| 49,960 | [
0.1370849609375,
0.249267578125,
0.224853515625,
0.3935546875,
-0.16064453125,
-0.205078125,
-0.4599609375,
-0.1494140625,
0.67333984375,
0.86328125,
0.60498046875,
-0.1923828125,
0.159912109375,
-0.63037109375,
-0.1737060546875,
-0.09405517578125,
-0.59521484375,
-0.57470703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Tags: implementation
Correct Solution:
```
n = int(input())
ans, p, s = 0, 0, 0
for i in range(n):
t, c = map(int, input().split())
s -= min(s, t - p)
p = t
s += c
if s > ans: ans = s
print(p + s, ans)
```
| 49,961 | [
0.1370849609375,
0.249267578125,
0.224853515625,
0.3935546875,
-0.16064453125,
-0.205078125,
-0.4599609375,
-0.1494140625,
0.67333984375,
0.86328125,
0.60498046875,
-0.1923828125,
0.159912109375,
-0.63037109375,
-0.1737060546875,
-0.09405517578125,
-0.59521484375,
-0.57470703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Tags: implementation
Correct Solution:
```
n = int(input())
message = 0
m = 0
l = 0
for _ in range(n):
t, c = map(int, input().split())
message = max(0, message-(t-l))
message += c
m = max(message, m)
l = t
print(l+message, m)
```
| 49,962 | [
0.1370849609375,
0.249267578125,
0.224853515625,
0.3935546875,
-0.16064453125,
-0.205078125,
-0.4599609375,
-0.1494140625,
0.67333984375,
0.86328125,
0.60498046875,
-0.1923828125,
0.159912109375,
-0.63037109375,
-0.1737060546875,
-0.09405517578125,
-0.59521484375,
-0.57470703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Tags: implementation
Correct Solution:
```
import sys
import math
n = int(input())
a, b = list(map(int, input().split()))
vmax = b
for i in range(1, n):
c, d = list(map(int, input().split()))
b = max(0, b - (c - a))
a = c
b += d
vmax = max(b, vmax)
print(a + b, vmax)
```
| 49,963 | [
0.1370849609375,
0.249267578125,
0.224853515625,
0.3935546875,
-0.16064453125,
-0.205078125,
-0.4599609375,
-0.1494140625,
0.67333984375,
0.86328125,
0.60498046875,
-0.1923828125,
0.159912109375,
-0.63037109375,
-0.1737060546875,
-0.09405517578125,
-0.59521484375,
-0.57470703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Tags: implementation
Correct Solution:
```
n = int(input())
ct = 0
cq = 0
mcq = 0
for i in range(n):
t, c = map(int, input().split())
mcq = max(cq, mcq)
cq = max(cq - (t - ct), 0)
cq += c
ct = t
#print(cq)
mcq = max(cq, mcq)
ct += cq
print(ct, mcq)
```
| 49,964 | [
0.1370849609375,
0.249267578125,
0.224853515625,
0.3935546875,
-0.16064453125,
-0.205078125,
-0.4599609375,
-0.1494140625,
0.67333984375,
0.86328125,
0.60498046875,
-0.1923828125,
0.159912109375,
-0.63037109375,
-0.1737060546875,
-0.09405517578125,
-0.59521484375,
-0.57470703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Tags: implementation
Correct Solution:
```
import re
import itertools
from collections import Counter, deque
class Task:
tasks = []
answer = ""
def getData(self):
numberOfTasks = int(input())
for i in range(0, numberOfTasks):
self.tasks += [[int(x) for x in input().split(' ')]]
#inFile = open('input.txt', 'r')
#inFile.readline().rstrip()
#self.childs = inFile.readline().rstrip()
def solve(self):
queueSize, maxQueueSize = 0, 0
time, timeOfLastMessage = 1, 1
currentTask = 0
while currentTask < len(self.tasks) or queueSize > 0:
maxQueueSize = max(maxQueueSize, queueSize)
if currentTask < len(self.tasks):
timeDelta = self.tasks[currentTask][0] - time
queueSize -= min(queueSize, timeDelta)
time += timeDelta
else:
timeOfLastMessage = time + queueSize
break
if currentTask < len(self.tasks) and \
self.tasks[currentTask][0] == time:
queueSize += self.tasks[currentTask][1]
currentTask += 1
self.answer = str(timeOfLastMessage) + " " + str(maxQueueSize)
def printAnswer(self):
print(self.answer)
#outFile = open('output.txt', 'w')
#outFile.write(self.answer)
task = Task()
task.getData()
task.solve()
task.printAnswer()
```
| 49,965 | [
0.1370849609375,
0.249267578125,
0.224853515625,
0.3935546875,
-0.16064453125,
-0.205078125,
-0.4599609375,
-0.1494140625,
0.67333984375,
0.86328125,
0.60498046875,
-0.1923828125,
0.159912109375,
-0.63037109375,
-0.1737060546875,
-0.09405517578125,
-0.59521484375,
-0.57470703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Tags: implementation
Correct Solution:
```
import sys
import math
#to read string
get_string = lambda: sys.stdin.readline().strip()
#to read list of integers
get_int_list = lambda: list( map(int,sys.stdin.readline().strip().split()) )
#to read integers
get_int = lambda: int(sys.stdin.readline())
#to print fast
pt = lambda x: sys.stdout.write(str(x)+'\n')
#--------------------------------WhiteHat010--------------------------------------#
n = get_int()
prev_t,s = get_int_list()
mx_q = s
q_size = s
for i in range(n-1):
t,s = get_int_list()
diff = t-prev_t
q_size = max(0,q_size - diff)
q_size = q_size + s
mx_q = max(mx_q, q_size)
prev_t = t
print(prev_t+q_size, mx_q)
```
| 49,966 | [
0.1370849609375,
0.249267578125,
0.224853515625,
0.3935546875,
-0.16064453125,
-0.205078125,
-0.4599609375,
-0.1494140625,
0.67333984375,
0.86328125,
0.60498046875,
-0.1923828125,
0.159912109375,
-0.63037109375,
-0.1737060546875,
-0.09405517578125,
-0.59521484375,
-0.57470703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Tags: implementation
Correct Solution:
```
import math
n = int(input())
q = 0
time = 0
high = 0
for _ in range(n):
recv, count = map(int, input().split())
if q > 0:
q = max( q - (recv-time), 0)
q += count
high = max(high, q)
time = recv
print(time+q,high)
```
| 49,967 | [
0.1370849609375,
0.249267578125,
0.224853515625,
0.3935546875,
-0.16064453125,
-0.205078125,
-0.4599609375,
-0.1494140625,
0.67333984375,
0.86328125,
0.60498046875,
-0.1923828125,
0.159912109375,
-0.63037109375,
-0.1737060546875,
-0.09405517578125,
-0.59521484375,
-0.57470703125,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Submitted Solution:
```
n = int(input())
l = []
for i in range(n):
c,t = map(int,input().split())
l.append((c,t))
queue = l[0][1]
z = queue
for i in range(1,n):
queue = queue - min((l[i][0]-l[i-1][0]),queue)
queue = queue + l[i][1]
z = max(z,queue)
print(l[-1][0]+queue,z)
```
Yes
| 49,968 | [
0.289306640625,
0.3623046875,
0.20849609375,
0.35205078125,
-0.1968994140625,
-0.1051025390625,
-0.48974609375,
-0.10125732421875,
0.6201171875,
0.81298828125,
0.623046875,
-0.1500244140625,
0.1380615234375,
-0.64111328125,
-0.1351318359375,
-0.1494140625,
-0.51708984375,
-0.558593... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Submitted Solution:
```
pt, s, vs = 0, 0, 0
for i in range(int(input())):
t, c = map(int, input().split())
s = max(s - (t - pt), 0) + c
vs = max(vs, s)
pt = t
print(pt + s, vs)
```
Yes
| 49,969 | [
0.289306640625,
0.3623046875,
0.20849609375,
0.35205078125,
-0.1968994140625,
-0.1051025390625,
-0.48974609375,
-0.10125732421875,
0.6201171875,
0.81298828125,
0.623046875,
-0.1500244140625,
0.1380615234375,
-0.64111328125,
-0.1351318359375,
-0.1494140625,
-0.51708984375,
-0.558593... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Submitted Solution:
```
Messages, Max, Last = 0, 0, 0
for i in range(int(input())):
X = list(map(int, input().split()))
Messages = max(0, Messages - (X[0] - Last))
Messages += X[1]
Max = max(Messages, Max)
Last = X[0]
print(Last + Messages, Max)
# UB_CodeForces
# Advice: Falling down is an accident, staying down is a choice
# Location: Mashhad for few days
# Caption: Finally happened what should be happened
# CodeNumber: 692
```
Yes
| 49,970 | [
0.289306640625,
0.3623046875,
0.20849609375,
0.35205078125,
-0.1968994140625,
-0.1051025390625,
-0.48974609375,
-0.10125732421875,
0.6201171875,
0.81298828125,
0.623046875,
-0.1500244140625,
0.1380615234375,
-0.64111328125,
-0.1351318359375,
-0.1494140625,
-0.51708984375,
-0.558593... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Submitted Solution:
```
n = int(input())
a1,a2 = 0,0
r = 0
for _ in range(n):
b1,b2 = map(int,input().split())
a2 = max(0,a2-(b1-a1))+b2
r = max(r,a2)
a1 = b1
print(a1+a2,r)
```
Yes
| 49,971 | [
0.289306640625,
0.3623046875,
0.20849609375,
0.35205078125,
-0.1968994140625,
-0.1051025390625,
-0.48974609375,
-0.10125732421875,
0.6201171875,
0.81298828125,
0.623046875,
-0.1500244140625,
0.1380615234375,
-0.64111328125,
-0.1351318359375,
-0.1494140625,
-0.51708984375,
-0.558593... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Submitted Solution:
```
n = int(input())
l = []
for i in range(n):
c,t = map(int,input().split())
l.append((c,t))
queue = l[0][1]
z = queue
for i in range(1,n):
queue = queue + l[i][1]
queue = queue - (l[i][0]-l[i-1][0])
z = max(z,queue)
if i > 0:
print(l[i][0]+queue,z)
else:
print(queue,z)
```
No
| 49,972 | [
0.289306640625,
0.3623046875,
0.20849609375,
0.35205078125,
-0.1968994140625,
-0.1051025390625,
-0.48974609375,
-0.10125732421875,
0.6201171875,
0.81298828125,
0.623046875,
-0.1500244140625,
0.1380615234375,
-0.64111328125,
-0.1351318359375,
-0.1494140625,
-0.51708984375,
-0.558593... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Submitted Solution:
```
n = int(input())
l = []
for i in range(n):
c,t = map(int,input().split())
l.append((c,t))
queue = l[0][1]
z = queue
for i in range(1,n):
queue = queue + l[i][1]
queue = queue - (l[i][0]-l[i-1][0])
z = max(z,queue)
print(l[-1][0]+queue,z)
```
No
| 49,973 | [
0.289306640625,
0.3623046875,
0.20849609375,
0.35205078125,
-0.1968994140625,
-0.1051025390625,
-0.48974609375,
-0.10125732421875,
0.6201171875,
0.81298828125,
0.623046875,
-0.1500244140625,
0.1380615234375,
-0.64111328125,
-0.1351318359375,
-0.1494140625,
-0.51708984375,
-0.558593... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Submitted Solution:
```
n = int(input())
l = []
for i in range(n):
c,t = map(int,input().split())
l.append((c,t))
queue = l[0][1]
z = queue
for i in range(1,n):
queue = queue + l[i][1]
queue = queue - (l[i][0]-l[i-1][0])
z = max(z,queue)
print(l[i][0]+queue,z)
```
No
| 49,974 | [
0.289306640625,
0.3623046875,
0.20849609375,
0.35205078125,
-0.1968994140625,
-0.1051025390625,
-0.48974609375,
-0.10125732421875,
0.6201171875,
0.81298828125,
0.623046875,
-0.1500244140625,
0.1380615234375,
-0.64111328125,
-0.1351318359375,
-0.1494140625,
-0.51708984375,
-0.558593... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
1. If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.
2. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
Input
The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).
Output
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
Examples
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
Note
In the first test sample:
* second 1: the first message has appeared in the queue, the queue's size is 1;
* second 2: the first message is sent, the second message has been received, the queue's size is 1;
* second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Submitted Solution:
```
n = int(input())
ans, p, s = 0, 0, 0
for i in range(n):
t, c = map(int, input().split())
s -= min(s, t - p)
p = t
s += c
if s > ans: ans = s
print(ans, p + s)
```
No
| 49,975 | [
0.289306640625,
0.3623046875,
0.20849609375,
0.35205078125,
-0.1968994140625,
-0.1051025390625,
-0.48974609375,
-0.10125732421875,
0.6201171875,
0.81298828125,
0.623046875,
-0.1500244140625,
0.1380615234375,
-0.64111328125,
-0.1351318359375,
-0.1494140625,
-0.51708984375,
-0.558593... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Tags: brute force, implementation, math
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
if n<=2:
print(0)
else:
q=[]
for i in range(-1,2):
for j in range(-1,2):
b=a[:]
count=abs(i)+abs(j)
b[0]+=i
b[1]+=j
flag=False
for k in range(2,n):
if abs(b[0]+k*(b[1]-b[0])-b[k])==1:
count+=1
elif abs(b[0]+k*(b[1]-b[0])-b[k])==0:
continue
else:
flag=True
break
if not flag:
q.append(count)
if len(q)!=0:
print(min(q))
else:
print(-1)
```
| 50,233 | [
0.357177734375,
0.08160400390625,
-0.013885498046875,
0.1500244140625,
-0.20361328125,
-0.033538818359375,
-0.61083984375,
-0.1732177734375,
0.09173583984375,
1.171875,
0.72119140625,
-0.1439208984375,
0.194580078125,
-1.1083984375,
-0.74658203125,
-0.0850830078125,
-0.95263671875,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Tags: brute force, implementation, math
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 15:16:08 2019
@author: IV_Ernst
"""
def main():
n = int(input())
bs = list( map(int, input().split(' ')))
if n < 3:
print(0)
return
mincount = n + 1
for c0 in [-1, 0, 1]:
for c1 in [-1, 0 , 1]:
# cs = [c0, c1]
c_current = c1
cnt = 0
if c0 != 0:
cnt += 1
if c1 != 0:
cnt += 1
# print('c0, c1 = ', (c0, c1))
d = bs[1] + c1 - (bs[0] + c0)
# t = True
for b, b_next in zip(bs[1:], bs[2:]):
# print((b, b_next))
c_next = d + b - b_next + c_current
c_current = c_next
if c_next not in [-1, 0, 1]:
# print('\tbreak')
break
if c_next != 0:
cnt += 1
else:
mincount = min(mincount, cnt)
# print('\telse')
if mincount > n:
print(-1)
else:
print(mincount)
if __name__ == '__main__':
main()
```
| 50,234 | [
0.357177734375,
0.08160400390625,
-0.013885498046875,
0.1500244140625,
-0.20361328125,
-0.033538818359375,
-0.61083984375,
-0.1732177734375,
0.09173583984375,
1.171875,
0.72119140625,
-0.1439208984375,
0.194580078125,
-1.1083984375,
-0.74658203125,
-0.0850830078125,
-0.95263671875,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Tags: brute force, implementation, math
Correct Solution:
```
import math
n = int(input())
lst = list(map(int,input().split()))
fin_ans = int(1e9)
if n<=2:
print(0)
else:
for el1 in range(lst[0]-1,lst[0]+2):
for el2 in range(lst[1]-1,lst[1]+2):
ans = abs(el1-lst[0])+abs(el2-lst[1])
fl = True
cur = el2
dif = el2-el1
for el in lst[2:]:
cur += dif
if abs(cur-el) > 1:
fl = False
break
ans += abs(cur-el)
if fl:
fin_ans = min(fin_ans,ans)
print(fin_ans if fin_ans<int(1e9) else -1)
```
| 50,235 | [
0.357177734375,
0.08160400390625,
-0.013885498046875,
0.1500244140625,
-0.20361328125,
-0.033538818359375,
-0.61083984375,
-0.1732177734375,
0.09173583984375,
1.171875,
0.72119140625,
-0.1439208984375,
0.194580078125,
-1.1083984375,
-0.74658203125,
-0.0850830078125,
-0.95263671875,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Tags: brute force, implementation, math
Correct Solution:
```
n=int(input())
b=list(map(int,input().split()))
lo=n+1
if n<=2:
print(0)
quit()
for i in range(-1,2):
for j in range(-1,2):
bol,c=1,0
if (b[0]+i-b[n-1]-j)%(n-1):
continue
d=-(b[0]+i-b[n-1]-j)//(n-1)
for k in range(1,n-1):
d0=b[k]-b[0]-i-d*k
if abs(d0)>1:
bol=0
break
elif d0:
c+=1
if bol:
lo=min(c+abs(i)+abs(j),lo)
if lo>n:
print(-1)
else:
print(lo)
```
| 50,236 | [
0.357177734375,
0.08160400390625,
-0.013885498046875,
0.1500244140625,
-0.20361328125,
-0.033538818359375,
-0.61083984375,
-0.1732177734375,
0.09173583984375,
1.171875,
0.72119140625,
-0.1439208984375,
0.194580078125,
-1.1083984375,
-0.74658203125,
-0.0850830078125,
-0.95263671875,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Tags: brute force, implementation, math
Correct Solution:
```
import sys
input = sys.stdin.readline
'''
a1, a2
a1+1, a2
a1+1, a2-1
a1+1, a2+1
'''
def sim(n, b, d):
cur = b[0]
count = 0
for i in range(1, n):
cur += d
diff = abs(b[i]-cur)
if diff == 0:
continue
elif diff == 1:
count += 1
else:
return float("inf")
return count
def solve(n, b):
if n <= 2:
return 0
a1, a2 = b[0], b[1]
d = a2 - a1
candidates = {d-2, d-1, d, d+1, d+2}
best = float("inf")
for d in candidates:
b[0] = a1
best = min(best, sim(n, b, d))
for first in [a1-1, a1+1]:
b[0] = first
best = min(best, sim(n, b, d)+1)
if best == float("inf"):
return -1
else:
return best
n = int(input())
b = list(map(int, input().split()))
print(solve(n, b))
```
| 50,237 | [
0.357177734375,
0.08160400390625,
-0.013885498046875,
0.1500244140625,
-0.20361328125,
-0.033538818359375,
-0.61083984375,
-0.1732177734375,
0.09173583984375,
1.171875,
0.72119140625,
-0.1439208984375,
0.194580078125,
-1.1083984375,
-0.74658203125,
-0.0850830078125,
-0.95263671875,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Tags: brute force, implementation, math
Correct Solution:
```
from sys import stdin, stdout
from sys import maxsize
#input = stdin.readline().strip
def solve(a, n):
# print(a)
d = (a[-1]-a[0])//(n-1)
m = set({-1, 0, 1})
count = 0
for i in range(n-2):
if(a[i]+d-a[i+1] in m):
if(a[i]+d-a[i+1] == -1):
count += 1
a[i+1] -= 1
if(a[i]+d-a[i+1] == 1):
count += 1
a[i+1] += 1
else:
return maxsize
if(a[n-2]+d-a[n-1] != 0):
return maxsize
return count
test = 1
# test = int(input())
for t in range(0, test):
# brr = [list(map(int,input().split())) for i in range(rows)] # 2D array row-wise input
n = int(input())
# s = list(input()) # String Input, converted to mutable list.
# n, x = list(map(int, input().split()))
arr = [int(x) for x in input().split()]
if(n == 1 or n == 2):
print(0)
break
m1 = solve(arr[:], n)
arr[-1] += 1
m2 = solve(arr[:], n)+1
arr[-1] -= 2
m3 = solve(arr[:], n)+1
arr[-1] += 1
arr[0] += 1
m4 = solve(arr[:], n)+1
arr[-1] += 1
m5 = solve(arr[:], n)+2
arr[-1] -= 2
m6 = solve(arr[:], n)+2
arr[-1] += 1
arr[0] -= 1
arr[0] += -1
m7 = solve(arr[:], n)+1
arr[-1] += 1
m8 = solve(arr[:], n)+2
arr[-1] -= 2
m9 = solve(arr[:], n)+2
ans = min(m1, m2, m3, m4, m5, m6, m7, m8, m9)
if(ans == maxsize):
print(-1)
else:
print(ans)
'''
rows, cols = (5, 5)
arr = [[0]*cols for j in range(rows)] # 2D array initialization
b=input().split() # list created by spliting about spaces
brr = [[int(b[cols*i+j]) for j in range(cols)] for i in range(rows)] # 2D array Linear Input
rows,cols=len(brr),len(brr[0]) # no of rows/cols for 2D array
arr.sort(key = lambda x : x[1]) # sort list of tuples by 2nd element, Default priority - 1st Element then 2nd Element
s=set() # empty set
a=maxsize # initializing infinity
b=-maxsize # initializing -infinity
mapped=list(map(function,input)) # to apply function to list element-wise
try: # Error handling
#code 1
except: # ex. to stop at EOF
#code 2 , if error occurs
'''
```
| 50,238 | [
0.357177734375,
0.08160400390625,
-0.013885498046875,
0.1500244140625,
-0.20361328125,
-0.033538818359375,
-0.61083984375,
-0.1732177734375,
0.09173583984375,
1.171875,
0.72119140625,
-0.1439208984375,
0.194580078125,
-1.1083984375,
-0.74658203125,
-0.0850830078125,
-0.95263671875,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Tags: brute force, implementation, math
Correct Solution:
```
def solve(n, a):
if n <= 2:
return 0
d = [v - u for u, v in zip(a, a[1:])]
max_d = max(d)
min_d = min(d)
if max_d - min_d > 4:
return -1
min_cnt = -1
for d in range(min_d, max_d + 1):
for d0 in range(-1, 2):
y = a[0] + d0
valid = True
cnt = 0 if d0 == 0 else 1
for x in a[1:]:
dx = abs(y + d - x)
if dx > 1:
valid = False
break
cnt += dx
y += d
if valid:
# print(d)
if cnt < min_cnt or min_cnt < 0:
min_cnt = cnt
return min_cnt
def main():
n = int(input())
a = [int(_) for _ in input().split()]
ans = solve(n, a)
print(ans)
if __name__ == '__main__':
main()
```
| 50,239 | [
0.357177734375,
0.08160400390625,
-0.013885498046875,
0.1500244140625,
-0.20361328125,
-0.033538818359375,
-0.61083984375,
-0.1732177734375,
0.09173583984375,
1.171875,
0.72119140625,
-0.1439208984375,
0.194580078125,
-1.1083984375,
-0.74658203125,
-0.0850830078125,
-0.95263671875,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Tags: brute force, implementation, math
Correct Solution:
```
n = int(input())
lis = list(map(int,input().split()))
if n==1:
print(0)
exit()
tmp=[-1,0,1]
fin=1000000000000
for i in tmp:
for j in tmp:
arr=lis[:]
arr[0]+=i
arr[1]+=j
dif=(arr[1])-(arr[0])
ans=0
if i!=0:
ans=1
if j!=0:
ans+=1
# print(arr,ans)
for k in range(2,n):
# print(arr[k],arr[k-1],dif)
aa=abs(arr[k]-(arr[k-1]+dif))
if aa==1:
ans+=1
arr[k]=arr[k-1]+dif
if aa>1:
ans=1000000000000
fin=min(ans,fin)
if fin==1000000000000:
print(-1)
else:
print(fin)
```
| 50,240 | [
0.357177734375,
0.08160400390625,
-0.013885498046875,
0.1500244140625,
-0.20361328125,
-0.033538818359375,
-0.61083984375,
-0.1732177734375,
0.09173583984375,
1.171875,
0.72119140625,
-0.1439208984375,
0.194580078125,
-1.1083984375,
-0.74658203125,
-0.0850830078125,
-0.95263671875,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Submitted Solution:
```
import collections
def solve(n, arr):
n = len(arr)
if n <= 2:
return 0
INF = float("inf")
minCount = INF
for d1 in [-1, 0, 1]:
for d2 in [-1, 0, 1]:
a1 = arr[0] + d1
a2 = arr[1] + d2
d = a2 - a1
count = abs(d1) + abs(d2)
isPossible = True
for i in range(2, n):
ai = a1 + i*d
if abs(ai-arr[i]) > 1:
isPossible = False
count += abs(ai-arr[i])
if isPossible:
minCount = min(minCount, count)
return -1 if minCount == INF else minCount
n = int(input().strip())
arr = list(map(int, input().strip().split()))
print(solve(n, arr))
```
Yes
| 50,241 | [
0.415771484375,
0.1456298828125,
-0.09674072265625,
0.142822265625,
-0.313232421875,
0.09326171875,
-0.7265625,
-0.152099609375,
0.0283050537109375,
1.103515625,
0.61669921875,
-0.1524658203125,
0.177490234375,
-1.046875,
-0.69580078125,
-0.1072998046875,
-0.85107421875,
-1.0400390... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Submitted Solution:
```
def get_arithmetic(b,count):
d = b[1] - b[0]
flag = True
for i in range(2,len(b)):
x = b[i-1] + d - b[i]
if(x != 0):
if(x == 1) or ((x == -1) and (b[i] != 0)):
b[i] += x
count += 1
else:
flag = False
break
if(flag == True):
return count
else:
return -1
def find_arithmetic_progression(a):
min_count = -1
# d = b2 - b1
b = [a[i] for i in range(0,len(a))]
count = get_arithmetic(b,0)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
# d = b2 - (b1 + 1)
b = [a[i] for i in range(0,len(a))]
b[0] += 1
count = get_arithmetic(b,1)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
# d = b2 - (b1 - 1)
b = [a[i] for i in range(0,len(a))]
if(b[0] != 0):
b[0] -= 1
count = get_arithmetic(b,1)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
# d = b2 + 1 - b1
b = [a[i] for i in range(0,len(a))]
b[1] += 1
count = get_arithmetic(b,1)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
# d = (b2 + 1) - (b1 + 1)
b = [a[i] for i in range(0,len(a))]
b[0] += 1
b[1] += 1
count = get_arithmetic(b,2)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
# d = (b2 + 1) - (b1 - 1)
b = [a[i] for i in range(0,len(a))]
if(b[0] != 0):
b[0] -= 1
b[1] += 1
count = get_arithmetic(b,2)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
# d = (b2 - 1) - b1
b = [a[i] for i in range(0,len(a))]
if(b[1] != 0):
b[1] -= 1
count = get_arithmetic(b,1)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
# d = (b2 - 1) - (b1 + 1)
b = [a[i] for i in range(0,len(a))]
if(b[1] != 0):
b[0] += 1
b[1] -= 1
count = get_arithmetic(b,2)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
# d = (b2 - 1) - (b1 - 1)
b = [a[i] for i in range(0,len(a))]
if(b[1] != 0) and (b[0] != 0):
b[0] -= 1
b[1] -= 1
count = get_arithmetic(b,2)
if(count != -1) and ((count < min_count) or (min_count == -1)):
min_count = count
return min_count
n = int(input())
if(n <= 2):
print(0)
else:
b = input().split(" ")
b = [int(b[i]) for i in range(0,len(b))]
print(find_arithmetic_progression(b))
```
Yes
| 50,242 | [
0.415771484375,
0.1456298828125,
-0.09674072265625,
0.142822265625,
-0.313232421875,
0.09326171875,
-0.7265625,
-0.152099609375,
0.0283050537109375,
1.103515625,
0.61669921875,
-0.1524658203125,
0.177490234375,
-1.046875,
-0.69580078125,
-0.1072998046875,
-0.85107421875,
-1.0400390... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Submitted Solution:
```
length = int(input())
l = input().split(" ")
l = [int(e) for e in l]
assert length == len(l)
if len(l) < 3:
print(0)
exit()
result = -1
for d0 in [-1, 0, 1]:
for d1 in [-1, 0, 1]:
for d2 in [-1, 0, 1]:
step = l[1] + d1 - (l[0] + d0)
if step != l[2] + d2 - (l[1] + d1):
continue
count = 0
for d in [d0, d1, d2]:
if d != 0:
count += 1
pre = l[2] + d2
for e in l[3:]:
d = e - pre - step
if d > 1 or d < -1:
count = -1
break
if d != 0:
count += 1
pre = e - d
if count == -1:
continue
if result == -1 or result > count:
result = count
print(result)
```
Yes
| 50,243 | [
0.415771484375,
0.1456298828125,
-0.09674072265625,
0.142822265625,
-0.313232421875,
0.09326171875,
-0.7265625,
-0.152099609375,
0.0283050537109375,
1.103515625,
0.61669921875,
-0.1524658203125,
0.177490234375,
-1.046875,
-0.69580078125,
-0.1072998046875,
-0.85107421875,
-1.0400390... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Submitted Solution:
```
n = [int(x) for x in input().rstrip().split()][0]
data = [int(x) for x in input().rstrip().split()]
is_found = False
nudges = [0, -1, 1]
last_idx = len(data) - 1
if n <= 2:
print(0)
exit()
if n == 3:
last_idx += 1
result = -1
for s_nudge in nudges:
for e_nudge in nudges:
s_val = data[0] + s_nudge
e_val = data[len(data) - 1] + e_nudge
if ((e_val - s_val) % (n-1)) == 0:
num_change = abs(e_nudge) + abs(s_nudge)
diff = (e_val - s_val) / (n-1)
val = s_val + diff
for idx in range(1, last_idx):
value = data[idx]
if abs(value - val) == 1:
num_change += 1
elif abs(value - val) > 1:
break
val += diff
if idx == last_idx - 1:
if result == -1 or result > num_change:
result = num_change
print(result)
```
Yes
| 50,244 | [
0.415771484375,
0.1456298828125,
-0.09674072265625,
0.142822265625,
-0.313232421875,
0.09326171875,
-0.7265625,
-0.152099609375,
0.0283050537109375,
1.103515625,
0.61669921875,
-0.1524658203125,
0.177490234375,
-1.046875,
-0.69580078125,
-0.1072998046875,
-0.85107421875,
-1.0400390... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Submitted Solution:
```
import sys
n=int(input())
list1=list(map(int,input().split()))
f=0
ff=0
cnt=0
if(n>2):
xx=list1[0]
yy=list1[1]
ll=list1.copy()
for i in range(-1,2):
for j in range(-1,2):
list1=ll.copy()
cnt=0
list1[0]=xx+i
if(i!=0):
cnt+=1
list1[1]=yy+j
if(j!=0):
cnt+=1
d=list1[1]-list1[0]
f=0
# print(list1[0],list1[1])
for ii in range(2,n):
if(list1[ii]-list1[ii-1]==d):
continue
elif(list1[ii]-list1[ii-1]==d+1):
list1[ii]-=1
cnt+=1
elif(list1[ii]-list1[ii-1]==d-1):
list1[ii]+=1
cnt+=1
else:
f=1
# print(list1)
if(f==0):
print(cnt)
sys.exit()
print(-1)
else:
print(0)
```
No
| 50,245 | [
0.415771484375,
0.1456298828125,
-0.09674072265625,
0.142822265625,
-0.313232421875,
0.09326171875,
-0.7265625,
-0.152099609375,
0.0283050537109375,
1.103515625,
0.61669921875,
-0.1524658203125,
0.177490234375,
-1.046875,
-0.69580078125,
-0.1072998046875,
-0.85107421875,
-1.0400390... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Submitted Solution:
```
n = int(input())
aaa = list(map(int,input().split()))
bbb = []
if n >= 2:
for i in range(1,n):
bbb.append(aaa[i] - aaa[i-1])
count = 0
if n == 1:
print(0)
elif max(bbb) - min(bbb) > 4:
print(-1)
else:
for i in range(len(bbb)):
count = count + abs(bbb[i]-max(bbb))
print(count)
```
No
| 50,246 | [
0.415771484375,
0.1456298828125,
-0.09674072265625,
0.142822265625,
-0.313232421875,
0.09326171875,
-0.7265625,
-0.152099609375,
0.0283050537109375,
1.103515625,
0.61669921875,
-0.1524658203125,
0.177490234375,
-1.046875,
-0.69580078125,
-0.1072998046875,
-0.85107421875,
-1.0400390... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Submitted Solution:
```
n=int(input())
if n<=2:
print(0)
exit()
a=list(map(int,input().split()))
b=a.copy()
k1=0
q=b[1]-b[0]
for i in range(2,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k1+=1
elif b[i-1]+q-b[i]==-1:
b[i]-=1
k1+=1
elif b[i-1]+q-b[i]==0:
pass
else:
k1=n+1
break
b=a.copy()
k2=2
b[0]-=1
b[1]-=1
q=b[1]-b[0]
for i in range(2,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k2+=1
elif b[i-1]+q-b[i]==-1:
a[i]-=1
k2+=1
elif b[i-1]+q-b[i]==0:
pass
else:
k2=n+1
break
b=a.copy()
k3=2
b[0]+=1
b[1]+=1
q=b[1]-b[0]
for i in range(2,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k3+=1
elif b[i-1]+q-b[i]==-1:
b[i]-=1
k3+=1
elif b[i-1]+q-a[i]==0:
pass
else:
k3=n+1
break
b=a.copy()
k4=1
b[1]+=1
q=b[1]-b[0]
for i in range(2,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k4+=1
elif b[i-1]+q-b[i]==-1:
b[i]-=1
k4+=1
elif b[i-1]+q-b[i]==0:
pass
else:
k4=n+1
break
b=a.copy()
k5=1
b[1]-=1
q=b[1]-b[0]
for i in range(1,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k5+=1
elif b[i-1]+q-b[i]==-1:
b[i]-=1
k5+=1
elif b[i-1]+q-b[i]==0:
pass
else:
k5=n+1
break
b=a.copy()
k6=1
b[0]+=1
q=b[1]-b[0]
for i in range(2,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k6+=1
elif b[i-1]+q-b[i]==-1:
b[i]-=1
k6+=1
elif b[i-1]+q-b[i]==0:
pass
else:
k6=n+1
break
b=a.copy()
k7=1
b[0]-=1
q=b[1]-b[0]
for i in range(2,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k7+=1
elif b[i-1]+q-b[i]==-1:
b[i]-=1
k7+=1
elif b[i-1]+q-b[i]==0:
pass
else:
k7=n+1
break
b=a.copy()
k8=2
b[0]+=1
b[1]-=1
q=b[1]-b[0]
for i in range(2,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k8+=1
elif b[i-1]+q-b[i]==-1:
b[i]-=1
k8+=1
elif b[i-1]+q-b[i]==0:
pass
else:
k8=n+1
break
b=a.copy()
k9=2
b[0]-=1
b[1]+=1
q=b[1]-b[0]
for i in range(2,n):
if b[i-1]+q-b[i]==1:
b[i]+=1
k9+=1
elif b[i-1]+q-b[i]==-1:
b[i]-=1
k9+=1
elif b[i-1]+q-b[i]==0:
pass
else:
k9=n+1
break
ans=min(k1,k2,k3,k4,k5,k6,k7,k8,k9)
if ans==n+1:
print(-1)
else:
print(ans)
```
No
| 50,247 | [
0.415771484375,
0.1456298828125,
-0.09674072265625,
0.142822265625,
-0.313232421875,
0.09326171875,
-0.7265625,
-0.152099609375,
0.0283050537109375,
1.103515625,
0.61669921875,
-0.1524658203125,
0.177490234375,
-1.046875,
-0.69580078125,
-0.1072998046875,
-0.85107421875,
-1.0400390... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers [b_1, b_2, ..., b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.
Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals 0.
Input
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in b.
The second line contains a sequence b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^{9}).
Output
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Examples
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
Note
In the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression.
Submitted Solution:
```
n = int(input())
bn = [int(i) for i in input().split(' ')]
def path(an, i = 0, d = 0, c = 0):
global n
if n == 1:
return 0
if i < n-1:
if i == 0:
dn = 0
an[i+1] += 1
dn = an[i+1] - an[i]
m1 = path(an, i+1, dn, c+1)
# reset
an[i+1] -= 1
dn = an[i+1] - an[i]
m2 = path(an, i+1, dn, c)
an[i+1] -= 1
dn = an[i+1] - an[i]
m3 = path(an, i+1, dn, c+1)
if m1 == None: m1 = 10**9 + 1
if m2 == None: m2 = 10**9 + 1
if m3 == None: m3 = 10**9 + 1
return min(m1, m2, m3)
else:
k = an[:]
k[i+1] += 1
dn = k[i+1] - k[i]
if d == dn:
return path(k, i+1, d, c+1)
# reset
k[i+1] -= 1
dn = k[i+1] - k[i]
if d == dn:
return path(k, i+1, d, c)
k[i+1] -= 1
dn = k[i+1] - k[i]
if dn == d:
return path(k, i+1, d, c+1)
del k
else:
return c
r1 = path(bn)
bn[0] += 1
r2 = path(bn) + 1
bn[0] -= 2
r3 = path(bn) + 1
if r1 >= 10**9+1 and r2 >= 10**9+1 and r3 >= 10**9+1:
print(-1)
else:
r = min(r1, r2, r3)
print(r)
```
No
| 50,248 | [
0.415771484375,
0.1456298828125,
-0.09674072265625,
0.142822265625,
-0.313232421875,
0.09326171875,
-0.7265625,
-0.152099609375,
0.0283050537109375,
1.103515625,
0.61669921875,
-0.1524658203125,
0.177490234375,
-1.046875,
-0.69580078125,
-0.1072998046875,
-0.85107421875,
-1.0400390... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Tags: implementation
Correct Solution:
```
s = input().split()[0]
cur = s[0]
curn = 0
res = 0
i = 0
#for i in range(len(s)):
while i < len(s):
if curn == 5:
curn = 0
res += 1
i -= 1
else:
if s[i] == cur:
curn += 1
else:
if curn != 0:
res += 1
curn = 1
cur = s[i]
i += 1
res += 1
#print(curn)
print(res)
```
| 50,655 | [
0.130615234375,
0.056549072265625,
0.372314453125,
0.123291015625,
-0.744140625,
-0.485595703125,
-0.355224609375,
0.35595703125,
0.386962890625,
0.67529296875,
0.79150390625,
-0.131103515625,
0.226318359375,
-0.609375,
-0.7001953125,
0.01953125,
-0.763671875,
-0.429443359375,
-0... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Tags: implementation
Correct Solution:
```
a=list(input())
r=a[0]
count=1
i=0
for j in a:
if i==5 or j!=r:
count+=1; i=1; r=j
else: i+=1
print(count)
```
| 50,656 | [
0.1324462890625,
0.051605224609375,
0.377197265625,
0.1195068359375,
-0.7353515625,
-0.50634765625,
-0.36865234375,
0.36328125,
0.377685546875,
0.67431640625,
0.78515625,
-0.1278076171875,
0.2357177734375,
-0.59375,
-0.7041015625,
0.033660888671875,
-0.77587890625,
-0.426513671875,... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Tags: implementation
Correct Solution:
```
s=input()
p="w"
k=0
k1=1
for x in s :
if x!=p :
k+=1
k1=1
p=x
else :
k1+=1
if k1==6 :
k+=1
k1=1
p=x
print(k)
```
| 50,657 | [
0.1405029296875,
0.0714111328125,
0.38232421875,
0.12213134765625,
-0.73974609375,
-0.490966796875,
-0.359130859375,
0.356201171875,
0.3662109375,
0.6875,
0.79443359375,
-0.130615234375,
0.2291259765625,
-0.61181640625,
-0.6962890625,
0.0175018310546875,
-0.78369140625,
-0.42602539... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Tags: implementation
Correct Solution:
```
prev = ''
h = 0
n = 0
for ch in input():
if ch != prev or h == 5:
h = 1
n += 1
else:
h += 1
prev = ch
print(n)
```
| 50,658 | [
0.13134765625,
0.06524658203125,
0.379150390625,
0.1331787109375,
-0.73583984375,
-0.496337890625,
-0.348388671875,
0.35107421875,
0.373046875,
0.69384765625,
0.81005859375,
-0.12445068359375,
0.2349853515625,
-0.6103515625,
-0.69189453125,
0.0166168212890625,
-0.7802734375,
-0.422... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Tags: implementation
Correct Solution:
```
a = input()
ans = 0
i = 0
while i < len(a):
j = i + 1
while j < len(a) and a[j] == a[i] and j - i < 5: j+=1
ans+=1
i = j
print(ans)
```
| 50,659 | [
0.1273193359375,
0.061279296875,
0.38232421875,
0.12481689453125,
-0.7529296875,
-0.499267578125,
-0.34814453125,
0.364013671875,
0.368896484375,
0.69287109375,
0.78662109375,
-0.1339111328125,
0.2232666015625,
-0.6162109375,
-0.69482421875,
0.0261993408203125,
-0.76904296875,
-0.4... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Tags: implementation
Correct Solution:
```
s=input()
count,a,t=0,0,s[0]
for i in s:
if i!=t or a==5:count,a=count+1,0
a,t=a+1,i
print(count+1)
```
| 50,660 | [
0.129150390625,
0.0694580078125,
0.36767578125,
0.130126953125,
-0.75341796875,
-0.485595703125,
-0.343505859375,
0.36181640625,
0.36181640625,
0.67724609375,
0.7841796875,
-0.13623046875,
0.219482421875,
-0.599609375,
-0.70458984375,
0.011016845703125,
-0.7685546875,
-0.4162597656... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Tags: implementation
Correct Solution:
```
s = input()
a = 0
t = 1
for i in range(1,len(s)):
if s[i-1]==s[i]:
t = t+1
else:
a = a+ (t+4)//5
t = 1
a = a+ (t+4)//5
print(a)
```
| 50,661 | [
0.13525390625,
0.072265625,
0.37548828125,
0.1436767578125,
-0.76025390625,
-0.4873046875,
-0.338134765625,
0.36328125,
0.35888671875,
0.69482421875,
0.78466796875,
-0.1253662109375,
0.2215576171875,
-0.6044921875,
-0.68359375,
0.0175323486328125,
-0.765625,
-0.437255859375,
-0.6... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Tags: implementation
Correct Solution:
```
s = input()
t = s[0]
num = 1
res = 1
for i in s[1::]:
if num >=5 or not i == t:
num = 1
t = i
res += 1
else:
t = i
num += 1
print(res)
```
| 50,662 | [
0.1461181640625,
0.0733642578125,
0.37841796875,
0.12158203125,
-0.759765625,
-0.485595703125,
-0.348876953125,
0.351806640625,
0.375244140625,
0.68359375,
0.7978515625,
-0.127685546875,
0.218505859375,
-0.60595703125,
-0.70263671875,
0.019073486328125,
-0.77001953125,
-0.407958984... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
s = input()
count = 0
ans = 1
for i in range(1, len(s)):
if count == 4 or (count <= 4 and s[i] != s[i - 1]):
count = 0
ans += 1
elif s[i] == s[i - 1]:
count += 1
if s[i] != s[i - 1] and count != 0:
ans += 1
count = 0
print(ans)
```
Yes
| 50,663 | [
0.1632080078125,
0.053375244140625,
0.349609375,
0.12890625,
-0.77734375,
-0.38427734375,
-0.391845703125,
0.47314453125,
0.305908203125,
0.703125,
0.80126953125,
-0.173828125,
0.185791015625,
-0.56884765625,
-0.6865234375,
0.0225372314453125,
-0.77099609375,
-0.46728515625,
-0.5... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
s = str(input())
i=0
count = 0
while len(s)>0:
if s[0]=='C':
temp = s.lstrip('C')
if len(s)-len(temp)>5:
s = s[5:]
else:
s = temp
count = count+1
else:
temp = s.lstrip('P')
if len(s)-len(temp)>5:
s = s[5:]
else:
s = temp
count = count+1
print(count)
```
Yes
| 50,664 | [
0.157958984375,
0.04833984375,
0.348876953125,
0.12091064453125,
-0.77978515625,
-0.385498046875,
-0.37646484375,
0.467529296875,
0.310791015625,
0.6904296875,
0.79296875,
-0.17431640625,
0.1849365234375,
-0.5712890625,
-0.69384765625,
0.00335693359375,
-0.7685546875,
-0.4575195312... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
a = input()
m = len(a)
k = 1
answ = 0
if m == 1:
print(1)
exit()
for i in range(1,m):
if a[i] == a[i-1]:
k += 1
else:
answ+=k//5+int(k%5!=0)
k = 1
if i == m-1:
answ+=k//5+int(k%5!=0)
print(answ)
```
Yes
| 50,665 | [
0.170654296875,
0.045562744140625,
0.3486328125,
0.119873046875,
-0.7822265625,
-0.3828125,
-0.3798828125,
0.4736328125,
0.30419921875,
0.701171875,
0.80322265625,
-0.16650390625,
0.191650390625,
-0.56494140625,
-0.6884765625,
0.01873779296875,
-0.77783203125,
-0.46728515625,
-0.... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
X = input()
Count, i = 0, 0
while i < len(X):
temp, S = X[i], 0
while i < len(X) and X[i] == temp and S != 5:
i, S = i + 1, S + 1
Count += 1
print(Count)
# UB_CodeForces
# Advice: Never ever give up
# Location: Behind my desk in the midnight
# Caption: I Got a cold
```
Yes
| 50,666 | [
0.1627197265625,
0.047698974609375,
0.35107421875,
0.114990234375,
-0.77734375,
-0.38232421875,
-0.378662109375,
0.464599609375,
0.31396484375,
0.68896484375,
0.80322265625,
-0.162353515625,
0.183349609375,
-0.572265625,
-0.69140625,
0.0141448974609375,
-0.77490234375,
-0.452392578... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
stena= input ()
vruke=0
pohodov=1
j=''
for i in stena:
if j=='':
j=i
else:
if i==j:
vruke+=1
else:
pohodov+=1
vruke=1
j=i
if vruke==5:
pohodov+=1
vruke=0
print (pohodov)
```
No
| 50,667 | [
0.1695556640625,
0.03857421875,
0.34326171875,
0.126953125,
-0.79296875,
-0.385498046875,
-0.380126953125,
0.473876953125,
0.302490234375,
0.7041015625,
0.8046875,
-0.15478515625,
0.193359375,
-0.56103515625,
-0.6787109375,
0.004375457763671875,
-0.77783203125,
-0.45654296875,
-0... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
a=input()
b=[i for i in a.split('P')]
c=[i for i in a.split('C')]
g=0
for i in range(len(b)):
if b[i]!='':
if len(b[i])<=5:
k=len(b[i])
if k<=5:
g+=1
else:
g+=len(b[i])//5
g+=1
for i in range(len(c)):
if c[i]!='':
if len(c[i])<=int(5):
j=len(c[i])
if j<=5:
g+=1
else:
g += len(c[i]) // 5
g += 1
print(g)
```
No
| 50,668 | [
0.161376953125,
0.0384521484375,
0.360595703125,
0.1417236328125,
-0.763671875,
-0.383544921875,
-0.36279296875,
0.45947265625,
0.2998046875,
0.70068359375,
0.82958984375,
-0.1767578125,
0.1932373046875,
-0.580078125,
-0.6943359375,
0.013671875,
-0.76513671875,
-0.44921875,
-0.60... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
s = input()
cur = s[0]
cnt = 1
ans = 0
for i in range(1, len(s)):
x = s[i]
if(cur != x):
ans = ans + 1
cnt = 1
cur = x
else:
if(cnt < 5):
cnt = cnt + 1
else:
ans = ans + 1
cnt = 1
cur = x
print (ans)
```
No
| 50,669 | [
0.159423828125,
0.04315185546875,
0.35595703125,
0.115966796875,
-0.77685546875,
-0.385498046875,
-0.3828125,
0.46435546875,
0.30224609375,
0.69384765625,
0.81201171875,
-0.1744384765625,
0.1883544921875,
-0.5634765625,
-0.68505859375,
0.01338958740234375,
-0.77685546875,
-0.445068... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number — the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
Submitted Solution:
```
s=input()
c=0
d=9
if(len(s)>1):
for i in range(len(s)-1):
if(s[i]!=s[i+1]):
c=c+1
d=0
else:
d=d+1
if(d==5):
d=0
c=c+1
if(s[-1]==s[-2] and d!=5):
c=c+1
elif(s[-1]!=s[-2]):
c=c+1
print(c)
else:
print(1)
```
No
| 50,670 | [
0.1612548828125,
0.050018310546875,
0.350341796875,
0.11553955078125,
-0.7744140625,
-0.38134765625,
-0.38037109375,
0.469482421875,
0.313232421875,
0.6943359375,
0.79736328125,
-0.1715087890625,
0.1883544921875,
-0.572265625,
-0.6923828125,
0.0022983551025390625,
-0.78369140625,
-... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The farmer Polycarp has a warehouse with hay, which can be represented as an n × m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai, j and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1 × 1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
* the total amount of hay remaining in the warehouse must be equal to k,
* the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,
* the height of at least one stack must remain the same as it was,
* for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
Input
The first line of the input contains three integers n, m (1 ≤ n, m ≤ 1000) and k (1 ≤ k ≤ 1018) — the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization.
Then n lines follow, each containing m positive integers ai, j (1 ≤ ai, j ≤ 109), where ai, j is equal to the number of cubic meters of hay making the hay stack on the i-th row and j-th column of the table.
Output
In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next n lines print m numbers — the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered.
If there are multiple answers, print any of them.
Examples
Input
2 3 35
10 4 9
9 9 7
Output
YES
7 0 7
7 7 7
Input
4 4 50
5 9 1 1
5 1 1 5
5 1 5 5
5 5 7 1
Output
YES
5 5 0 0
5 0 0 5
5 0 5 5
5 5 5 0
Input
2 4 12
1 1 3 1
1 6 2 4
Output
NO
Note
In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value k = 7·5 = 35. At that the stack that is on the second line and third row remained unaltered.
Submitted Solution:
```
#import primesieve as ps
import itertools as it
import functools as ft
import operator as op
import collections as cl
def iterate(f,x,recursion = 0):
if recursion == 0:
while True:
yield x
x = f(x)
else:
for _ in range(recursion + 1):
yield x
x = f(x)
def primes():
ps = [2]
yield 2
cand = 3
while True:
for p in ps:
if p*p > cand:
ps.append(cand)
yield cand
break
elif cand % p == 0:
break
cand += 2
def factorize(n):
pg = primes()
p = next(pg)
ret = []
while p*p <= n:
if n % p == 0:
ret.append(p)
n //= p
continue
p = next(pg)
return ret + [n]
def divisors(n):
fs = list(map(lambda x:list(x[1]), it.groupby(factorize(n))))
gs = list(map(lambda xs:list(iterate(lambda y:xs[0]*y, 1, len(xs))), fs))
return sorted(map(lambda xs:ft.reduce(op.mul, xs), it.product(*gs)))
n, m, k = map(int, input().split(' '))
inputs = [[] for _ in range(n)]
for i in range(n):
inputs[i] = list(map(int, input().split(' ')))
for d in reversed(list(it.takewhile(lambda x:x <= n*m, divisors(k)))):
e = k // d
vs = set()
paths = cl.defaultdict(list)
visited = set()
count = 0
ans = set()
result = 'NO'
for i in range(n):
for j in range(m):
if inputs[i][j] < e:
inputs[i][j] = 0
else:
vs.add((i,j))
if (i-1,j) in vs:
paths[(i-1,j)].append((i,j))
paths[(i,j)].append((i-1,j))
if (i,j-1) in vs:
paths[(i,j-1)].append((i,j))
paths[(i,j)].append((i,j-1))
if len(vs) < d:
continue
def search(v, n):
global count
if v in visited:
return False
count += 1
ans.add(v)
visited.add(v)
if count >= n:
return True
for u in paths[v]:
paths[u].remove(v)
if search(u, n):
return True
return False
for v in vs:
if v in visited:
continue
count = 0
ans.clear()
if search(v, d):
result = 'YES'
for i in range(n):
for j in range(m):
if (i,j) in ans:
inputs[i][j] = e
else:
inputs[i][j] = 0
break
if result == 'YES':
break
print(result)
if result == 'YES':
for i in range(n):
print(' '.join(map(str, inputs[i])))
```
No
| 51,754 | [
0.377197265625,
0.2197265625,
0.4697265625,
0.146484375,
-0.4560546875,
-0.036224365234375,
-0.145751953125,
0.05963134765625,
0.319580078125,
0.64111328125,
0.95361328125,
-0.1251220703125,
-0.250244140625,
-0.66357421875,
-0.6640625,
0.3173828125,
-0.5078125,
-0.66748046875,
-0... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The farmer Polycarp has a warehouse with hay, which can be represented as an n × m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai, j and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1 × 1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
* the total amount of hay remaining in the warehouse must be equal to k,
* the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,
* the height of at least one stack must remain the same as it was,
* for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
Input
The first line of the input contains three integers n, m (1 ≤ n, m ≤ 1000) and k (1 ≤ k ≤ 1018) — the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization.
Then n lines follow, each containing m positive integers ai, j (1 ≤ ai, j ≤ 109), where ai, j is equal to the number of cubic meters of hay making the hay stack on the i-th row and j-th column of the table.
Output
In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next n lines print m numbers — the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered.
If there are multiple answers, print any of them.
Examples
Input
2 3 35
10 4 9
9 9 7
Output
YES
7 0 7
7 7 7
Input
4 4 50
5 9 1 1
5 1 1 5
5 1 5 5
5 5 7 1
Output
YES
5 5 0 0
5 0 0 5
5 0 5 5
5 5 5 0
Input
2 4 12
1 1 3 1
1 6 2 4
Output
NO
Note
In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value k = 7·5 = 35. At that the stack that is on the second line and third row remained unaltered.
Submitted Solution:
```
class Stack(object):
def __init__(self):
self.items = []
def push(self,new):
self.items.append(new)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def empty(self):
return self.items == []
def size(self):
return len(self.items)
from bisect import bisect_left
(n,m,k) = map(int,input().split())
G = [None for i in range(n)]
all_number = []
for i in range(n):
line = list(map(int,input().split()))
G[i] = line
all_number.extend(line)
all_number.sort()
possible = []
for i in set(all_number):
if i > 0 and k % i == 0 and n*m - bisect_left(all_number,i) >= k // i:
possible.append(i)
visited = [[False for j in range(m)] for i in range(n)]
bool = False
print(possible)
for cand in possible:
L = []
for i in range(n):
if cand in G[i]:
j = G[i].index(cand)
break
Q = Stack()
Q.push((i,j))
L.append((i,j))
visited[i][j] = True
while not Q.empty():
r = Q.pop()
x,y = r[0],r[1]
for t in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]:
if abs(t[0]-(n-1)/2) <= (n-1)/2 and abs(t[1]-(m-1)/2) <= (m-1)/2 and G[t[0]][t[1]] >= cand and not visited[t[0]][t[1]]:
Q.push(t)
L.append(t)
visited[t[0]][t[1]] = True
print(L)
if len(L) >= k // cand:
answer = [["0" for j in range(m)] for i in range(n)]
for x in range(k // cand):
answer[L[x][0]][L[x][1]] = str(cand)
print("YES")
for i in answer:
print(' '.join(i))
bool = True
break
if not bool:
print("NO")
```
No
| 51,755 | [
0.377197265625,
0.2197265625,
0.4697265625,
0.146484375,
-0.4560546875,
-0.036224365234375,
-0.145751953125,
0.05963134765625,
0.319580078125,
0.64111328125,
0.95361328125,
-0.1251220703125,
-0.250244140625,
-0.66357421875,
-0.6640625,
0.3173828125,
-0.5078125,
-0.66748046875,
-0... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The farmer Polycarp has a warehouse with hay, which can be represented as an n × m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai, j and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1 × 1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
* the total amount of hay remaining in the warehouse must be equal to k,
* the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,
* the height of at least one stack must remain the same as it was,
* for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
Input
The first line of the input contains three integers n, m (1 ≤ n, m ≤ 1000) and k (1 ≤ k ≤ 1018) — the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization.
Then n lines follow, each containing m positive integers ai, j (1 ≤ ai, j ≤ 109), where ai, j is equal to the number of cubic meters of hay making the hay stack on the i-th row and j-th column of the table.
Output
In the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next n lines print m numbers — the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered.
If there are multiple answers, print any of them.
Examples
Input
2 3 35
10 4 9
9 9 7
Output
YES
7 0 7
7 7 7
Input
4 4 50
5 9 1 1
5 1 1 5
5 1 5 5
5 5 7 1
Output
YES
5 5 0 0
5 0 0 5
5 0 5 5
5 5 5 0
Input
2 4 12
1 1 3 1
1 6 2 4
Output
NO
Note
In the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value k = 7·5 = 35. At that the stack that is on the second line and third row remained unaltered.
Submitted Solution:
```
#import primesieve as ps
import itertools as it
import functools as ft
import operator as op
import collections as cl
def iterate(f,x,recursion = 0):
if recursion == 0:
while True:
yield x
x = f(x)
else:
for _ in range(recursion + 1):
yield x
x = f(x)
def primes():
ps = [2]
yield 2
cand = 3
while True:
for p in ps:
if p*p > cand:
ps.append(cand)
yield cand
break
elif cand % p == 0:
break
cand += 2
def factorize(n):
pg = primes()
p = next(pg)
ret = []
while p*p <= n:
if n % p == 0:
ret.append(p)
n //= p
continue
p = next(pg)
return ret + [n]
def divisors(n):
fs = list(map(lambda x:list(x[1]), it.groupby(factorize(n))))
gs = list(map(lambda xs:list(iterate(lambda y:xs[0]*y, 1, len(xs))), fs))
return sorted(map(lambda xs:ft.reduce(op.mul, xs), it.product(*gs)))
n, m, k = map(int, input().split(' '))
inputs = [[] for _ in range(n)]
for i in range(n):
inputs[i] = list(map(int, input().split(' ')))
for d in reversed(list(it.takewhile(lambda x:x <= n*m, divisors(k)))[1:]):
e = k // d
vs = set()
paths = cl.defaultdict(list)
visited = set()
count = 0
ans = set()
result = 'NO'
for i in range(n):
for j in range(m):
if inputs[i][j] < e:
inputs[i][j] = 0
else:
vs.add((i,j))
if (i-1,j) in vs:
paths[(i-1,j)].append((i,j))
paths[(i,j)].append((i-1,j))
if (i,j-1) in vs:
paths[(i,j-1)].append((i,j))
paths[(i,j)].append((i,j-1))
if len(vs) < d:
continue
def search(v, n):
global count
if v in visited:
return False
count += 1
ans.add(v)
visited.add(v)
if count >= n:
return True
for u in paths[v]:
paths[u].remove(v)
if search(u, n):
return True
return False
for v in vs:
if v in visited:
continue
count = 0
ans.clear()
if search(v, d):
result = 'YES'
for i in range(n):
for j in range(m):
if (i,j) in ans:
inputs[i][j] = e
else:
inputs[i][j] = 0
break
if result == 'YES':
break
print(result)
if result == 'YES':
for i in range(n):
print(' '.join(map(str, inputs[i])))
```
No
| 51,756 | [
0.377197265625,
0.2197265625,
0.4697265625,
0.146484375,
-0.4560546875,
-0.036224365234375,
-0.145751953125,
0.05963134765625,
0.319580078125,
0.64111328125,
0.95361328125,
-0.1251220703125,
-0.250244140625,
-0.66357421875,
-0.6640625,
0.3173828125,
-0.5078125,
-0.66748046875,
-0... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
#
import collections, atexit, math, sys, bisect
sys.setrecursionlimit(1000000)
def getIntList():
return list(map(int, input().split()))
try :
#raise ModuleNotFoundError
import numpy
def dprint(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
# in python 3.4 **kwargs is invalid???
print(*args, file=sys.stderr)
dprint('debug mode')
except Exception:
def dprint(*args, **kwargs):
pass
inId = 0
outId = 0
if inId>0:
dprint('use input', inId)
sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
dprint('use output', outId)
sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
atexit.register(lambda :sys.stdout.close()) #idle 中不会执行 atexit
N = getIntList()
za = getIntList()
cc = collections.Counter(za)
zt = []
for x in cc:
zt.append( cc[x] )
zt.sort( )
re = zt[-1]
def findmid(l,r, e):
if l>= len(zt):
return -1
if e<=zt[l]: return l;
if e>zt[r]: return -1
while l+1 <r:
mid = (l+r)//2
if zt[mid] < e:
l = mid
else:
r = mid
return r
for first in range(1, re//2 + 1):
nowr = 0
t = first
ind = -1
while 1:
ind = findmid(ind+1,len(zt)-1, t)
if ind<0:
break
nowr += t
t*=2
re = max(re, nowr)
print(re)
```
| 53,067 | [
0.62548828125,
0.048187255859375,
0.1502685546875,
0.25732421875,
-0.36572265625,
-0.38330078125,
-0.51318359375,
0.1353759765625,
0.29296875,
0.54296875,
0.65283203125,
-0.42822265625,
0.164306640625,
-0.60400390625,
-0.443115234375,
-0.256591796875,
-0.662109375,
-0.65625,
-0.9... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
p_line = [int(x) for x in input().strip().split(' ')]
size = p_line[0]
a = [int(x) for x in input().strip().split(' ')]
num_to_occ = {}
for x in a:
if x not in num_to_occ:
num_to_occ[x] = 0
num_to_occ[x] += 1
topics = []
for _, occ in num_to_occ.items():
topics.append(occ)
topics.sort(reverse = True)
ba = 0
for start in range(1, topics[0] + 1):
my_a = start
act = start
for i in range(1, len(topics)):
if act % 2 == 1:
break
act = act / 2
if act > 0 and topics[i] >= act:
my_a += act
else:
break
ba = max(ba, my_a)
print(int(ba))
```
| 53,068 | [
0.67822265625,
0.0562744140625,
0.1737060546875,
0.207763671875,
-0.359619140625,
-0.390625,
-0.483642578125,
0.1839599609375,
0.28515625,
0.53759765625,
0.6630859375,
-0.415771484375,
0.1123046875,
-0.64208984375,
-0.449951171875,
-0.291748046875,
-0.638671875,
-0.634765625,
-0.... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
from collections import Counter
def GPSum(a,r,n):
return (a*(pow(r,n)-1))//(r-1)
n = int(input())
aa = [int(i) for i in input().split()]
c = Counter(aa)
ss = sorted([int(i) for i in c.values()])[::-1]
# print(ss)
minn = [ss[0]]
cur = ss[0]
ans = ss[0]
for i in range(0,len(ss)):
if i == 0:
ans = ss[0]
else:
cur = min(cur//2,ss[i])
if cur:
ans = max(ans,GPSum(cur,2,i+1))
# print(minn)
print(ans)
```
| 53,069 | [
0.69921875,
0.06439208984375,
0.1552734375,
0.22900390625,
-0.35888671875,
-0.3681640625,
-0.466552734375,
0.16162109375,
0.314697265625,
0.52001953125,
0.67431640625,
-0.41796875,
0.1390380859375,
-0.654296875,
-0.41357421875,
-0.261474609375,
-0.63427734375,
-0.6123046875,
-0.9... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
def check(x):
ans=0
for i in range(len(fre)):
if fre[i]>=x:
ans+=x
else:
break
if x%2:
break
x=x//2
if x==0:
break
return ans
n = int(input())
lis = list(map(int,input().split()))
d={}
fre=[]
for i in lis:
if i in d:
d[i]+=1
else:
d[i]=1
for i in d:
fre.append(d[i])
fre.sort(reverse = True)
ans=0
for i in range(fre[0]+1):
ans=max(ans,check(i))
print(ans)
```
| 53,070 | [
0.671875,
0.04302978515625,
0.1689453125,
0.2330322265625,
-0.322998046875,
-0.414306640625,
-0.505859375,
0.1854248046875,
0.279052734375,
0.5361328125,
0.6923828125,
-0.40771484375,
0.1383056640625,
-0.6259765625,
-0.425048828125,
-0.26708984375,
-0.6796875,
-0.62255859375,
-0.... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
def main():
buf = input()
n = int(buf)
buf = input()
buflist = buf.split()
a = list(map(int, buflist))
appearance = {}
for i in a:
if not i in appearance:
appearance.update({i : 1})
else:
appearance[i] += 1
appearance = [[k, v] for k ,v in dict(sorted(appearance.items(), key=lambda x:x[1])).items()]
max_num = appearance[-1][1]
pos = 0
for i in range(1, max_num + 1):
num = 0
prob = i
for j in range(pos, len(appearance)):
if appearance[j][1] >= prob:
num += prob
prob *= 2
if num > max_num:
max_num = num
while appearance[pos][1] == i and pos < len(appearance) - 1:
pos += 1
print(max_num)
if __name__ == '__main__':
main()
```
| 53,071 | [
0.67919921875,
0.0633544921875,
0.150634765625,
0.20751953125,
-0.310791015625,
-0.402587890625,
-0.499267578125,
0.2000732421875,
0.280029296875,
0.517578125,
0.66845703125,
-0.4365234375,
0.1552734375,
-0.662109375,
-0.4052734375,
-0.320556640625,
-0.6484375,
-0.64208984375,
-0... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
# import sys
# input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
b={}
for i in range(n):
if a[i] not in b.keys():
b[a[i]]=0
b[a[i]]+=1
c=[]
for i in b:
c.append(b[i])
e=sorted(c,reverse=True)
d=[e[0]]
a=e[0]
for i in range(len(c)-1):
a=min(e[i+1],a//2)
d.append(a*(2**(i+2)-1))
if a==0:
break
print(max(d))
```
| 53,072 | [
0.67236328125,
0.046875,
0.183837890625,
0.200927734375,
-0.354248046875,
-0.37060546875,
-0.498046875,
0.173095703125,
0.25634765625,
0.54931640625,
0.64111328125,
-0.422607421875,
0.13330078125,
-0.640625,
-0.42529296875,
-0.3125,
-0.625,
-0.6298828125,
-0.9326171875,
-0.0370... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
import bisect
import sys
input=sys.stdin.readline
n=int(input())
ar=list(map(int,input().split()))
dic={}
for i in ar:
if(i in dic):
dic[i]+=1
else:
dic[i]=1
li=list(dic.values())
li.sort()
ans=max(li)
le=len(li)
for i in range(1,n+1):
l=0
r=le
po=0
st=i
while(l!=r):
xx=bisect.bisect(li,st,l,r)
if(xx==l):
l+=1
po+=1
st*=2
elif(xx==le):
if(st>li[-1]):
break
elif(st==li[-1]):
po+=1
break
else:
if(st==li[xx-1]):
l=xx
else:
l=xx+1
po+=1
st*=2
ans=max(ans,i*(2**po-1))
print(ans)
```
| 53,073 | [
0.63916015625,
0.08544921875,
0.2095947265625,
0.208984375,
-0.40087890625,
-0.353271484375,
-0.482177734375,
0.11212158203125,
0.250244140625,
0.5576171875,
0.65478515625,
-0.421630859375,
0.1456298828125,
-0.6904296875,
-0.44775390625,
-0.313720703125,
-0.63818359375,
-0.65380859... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
from collections import Counter,defaultdict
n=int(input())
l=list(map(int,input().split()))
c=Counter(l)
l1=[]
for i in c:
l1.append(c[i])
l1.sort()
ans=l1[-1]
l2=[defaultdict(int) for i in range(len(l1))]
for i in range(len(l1)):
a=1
while a<=l1[i]:
if l2[i][a]==1:
a+=1
continue
c=a
j=i+1
x=a
while j<len(l1) and l1[j]>=2*x:
l2[j][2*x]=1
c+=2*x
x*=2
j+=1
ans=max(ans,c)
a+=1
print(ans)
```
| 53,074 | [
0.66162109375,
0.06866455078125,
0.1351318359375,
0.1962890625,
-0.356689453125,
-0.363525390625,
-0.50830078125,
0.1734619140625,
0.285400390625,
0.52294921875,
0.62841796875,
-0.458984375,
0.1346435546875,
-0.66064453125,
-0.4658203125,
-0.3310546875,
-0.69580078125,
-0.61328125,... | 24 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Tags: greedy, sortings
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
for i in arr:
stdout.write(str(i)+' ')
stdout.write('\n')
range = xrange # not for python 3.0+
n=input()
l=map(int,raw_input().split())
d=Counter(l)
l=d.values()
n=len(l)
l.sort()
ans=0
for i in range(1,l[-1]+1):
pos=n-1
cur=i
temp=i
while cur%2==0 and pos:
cur/=2
pos-=1
if l[pos]<cur:
break
temp+=cur
ans=max(ans,temp)
print ans
```
| 53,075 | [
0.6142578125,
0.07818603515625,
0.192626953125,
0.233642578125,
-0.428955078125,
-0.423828125,
-0.58056640625,
0.1627197265625,
0.272705078125,
0.57373046875,
0.67578125,
-0.430419921875,
0.1500244140625,
-0.5869140625,
-0.481201171875,
-0.27490234375,
-0.6396484375,
-0.67138671875... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from collections import Counter
n = int(input())
a = sorted(Counter(map(int, input().split())).values())
n = len(a)
ans = 0
for j in range(1, a[-1] + 1):
tt = j
i = n - 1
while not j & 1 and i > 0:
j //= 2
i -= 1
if a[i] < j:
break
tt += j
ans = max(ans, tt)
print(ans)
```
Yes
| 53,076 | [
0.697265625,
0.12286376953125,
0.052032470703125,
0.1719970703125,
-0.427001953125,
-0.260498046875,
-0.497802734375,
0.274169921875,
0.1607666015625,
0.57958984375,
0.60107421875,
-0.35205078125,
0.17041015625,
-0.65283203125,
-0.3798828125,
-0.2279052734375,
-0.6826171875,
-0.566... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from collections import defaultdict
import bisect
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
cnt = defaultdict(lambda : 0)
for i in a:
cnt[i] += 1
x = [cnt[i] for i in cnt]
x.sort()
ans = 0
l = x[-1]
for i in range(1, l + 1):
y = bisect.bisect_left(x, i - 0.5)
j = 2 * i
cnt = i
while True:
z = bisect.bisect_left(x, j - 0.5)
if y >= z:
z = y + 1
if z == len(x):
ans = max(ans, cnt)
break
y = z
cnt += j
j *= 2
print(ans)
```
Yes
| 53,077 | [
0.67626953125,
0.139892578125,
0.07958984375,
0.1876220703125,
-0.4609375,
-0.227294921875,
-0.49462890625,
0.2359619140625,
0.1558837890625,
0.59228515625,
0.58251953125,
-0.335205078125,
0.1553955078125,
-0.67431640625,
-0.3876953125,
-0.2403564453125,
-0.669921875,
-0.5913085937... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
def main():
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
dic = dict()
for i in a:
if dic.get(i) is None:
dic[i] = 1
else:
dic[i] += 1
b = list(dic.values())
b.sort()
def solve(first):
x = first
i = -1
m = len(b)
ret = 0
while i+1 < m:
l, r = i+1, m-1
while l <= r:
mid = (l + r) // 2
if b[mid] >= x:
i = mid
r = mid - 1
else:
l = mid + 1
if i < l:
break
ret += x
x *= 2
return ret
ans = 0
for i in range(1, n+1):
ans = max(ans, solve(i))
print(ans)
main()
```
Yes
| 53,078 | [
0.705078125,
0.11236572265625,
0.0946044921875,
0.1614990234375,
-0.421630859375,
-0.23193359375,
-0.513671875,
0.24853515625,
0.1529541015625,
0.56591796875,
0.57958984375,
-0.343017578125,
0.135009765625,
-0.64404296875,
-0.3681640625,
-0.2352294921875,
-0.6416015625,
-0.55859375... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from collections import *
from math import *
def ch(mx):
if(mx > n):
return 0
m = l[0]//(1<<(mx-1))
for i in range(mx):
m = min(m,l[i]//(1<<(mx-i-1)))
return m*((1<<mx)-1)
n = int(input())
mx = ceil(log(n,2))
a = list(map(int,input().split()))
c = Counter(a)
l = list(c.values())
l.sort(reverse = True)
n = len(l)
ans = 1
for i in range(1,mx+1):
ans = max(ans,ch(i))
print(ans)
```
Yes
| 53,079 | [
0.6806640625,
0.1168212890625,
0.0703125,
0.193115234375,
-0.439208984375,
-0.2406005859375,
-0.5,
0.2900390625,
0.16357421875,
0.58837890625,
0.6220703125,
-0.324951171875,
0.147216796875,
-0.6455078125,
-0.38134765625,
-0.1881103515625,
-0.6572265625,
-0.56201171875,
-0.8413085... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
#------------------Sublime--------------------------------------#
sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(input()))
def In():return(map(int,input().split()))
else:
#------------------PYPY FAst I/o--------------------------------#
def I():return (int(stdin.readline()))
def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n=I()
l=list(In())
d=dict(l)
z=[]
for x in d:
z.append(d[x])
z.sort()
#print(z)
count=0
n1=len(z)
for i in range(1,(z[-1])+1):
ans=0
temp=i
j=0
while temp<=z[-1] and j<n1:
pos=find_gt(z,temp)
if pos==-1:
break
else:
ans+=temp
temp*=2
j+=1
if ans>count:
count=ans
#print(i)
print(count)
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
#for _ in range(I()):main()
for _ in range(1):main()
```
No
| 53,080 | [
0.6591796875,
0.0899658203125,
0.04925537109375,
0.2078857421875,
-0.46728515625,
-0.303466796875,
-0.54052734375,
0.2335205078125,
0.1717529296875,
0.59716796875,
0.5947265625,
-0.358642578125,
0.149658203125,
-0.63671875,
-0.423583984375,
-0.2149658203125,
-0.65234375,
-0.5737304... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
n=int(input())
d=dict()
l=list(map(int,input().split()))
for i in range(n):
if l[i] not in d:
d.update({l[i]:1})
else:
d[l[i]]+=1
if len(d)==1:
for j in d:
print(d[j])
else:
ans1=0
if len(d)<=44:
a=[]
for j in sorted(d.values()):
a.append(j)
ans1=0
for i in range(len(a)):
e=a[i]
ans=0
for j in range(i+1,len(a)):
if e*2<=a[j]:
ans+=2*e
e*=2
else:
break
e=a[i]
for j in range(i,-1,-1):
if e%2!=0:
break
else:
ans+=e
e=e//2
ans1=max(ans1,ans)
e=a[i]-1
ans=0
for j in range(i+1,len(a)):
if e*2<=a[j]:
ans+=2*e
e*=2
else:
break
e=a[i]-1
for j in range(i,-1,-1):
if e%2!=0:
break
else:
ans+=e
e=e//2
ans1=max(ans1,ans)
t=0
ans=0
rt=1
for j in sorted(d.values(),reverse=True):
if t==0:
ans+=j
prev=j
t+=1
rt=1
else:
if t<=44:
rt=rt*2
e=prev//2
#print(e,rt)
if j>=e:
if e*2==prev:
ans+=e
prev=e
else:
if t<=28 and e>=rt-1:
ans+=e-rt+1
prev=e
else:
break
else:
if t>44 or (rt*2-1)*j>=ans:
ans=(rt*2-1)*j
prev=j
else:
break
t+=1
print(max(ans1,ans))
```
No
| 53,081 | [
0.689453125,
0.1326904296875,
0.05078125,
0.2044677734375,
-0.4267578125,
-0.252197265625,
-0.498291015625,
0.292236328125,
0.1644287109375,
0.58203125,
0.595703125,
-0.340576171875,
0.1427001953125,
-0.6611328125,
-0.384033203125,
-0.2388916015625,
-0.68212890625,
-0.5546875,
-0... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
from collections import Counter
n = map(int,input().split())
arr = [int(x) for x in input().split()]
d = Counter(arr)
val = sorted(d.values(),reverse = True)
m = len(val)
ans = 0
fl = 0
for i in range(m-1):
if(val[i]//2<=val[i]+1):
ans+=2*val[i]//2
if(m==1):
print(*n)
else:
print(ans)
```
No
| 53,082 | [
0.68359375,
0.13427734375,
0.037384033203125,
0.18505859375,
-0.41943359375,
-0.25927734375,
-0.4990234375,
0.281005859375,
0.190185546875,
0.57421875,
0.60107421875,
-0.346923828125,
0.158935546875,
-0.6748046875,
-0.37548828125,
-0.229248046875,
-0.6708984375,
-0.58447265625,
-... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
* number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
* the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem.
Output
Print one integer — the maximum number of problems in the set of thematic contests.
Examples
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10
Output
14
Input
10
6 6 6 3 6 1000000000 3 3 6 6
Output
9
Input
3
1337 1337 1337
Output
3
Note
In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.
In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.
In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
Submitted Solution:
```
n=int(input())
d=dict()
l=list(map(int,input().split()))
for i in range(n):
if l[i] not in d:
d.update({l[i]:1})
else:
d[l[i]]+=1
if len(d)==1:
for j in d:
print(d[j])
else:
t=0
ans=0
rt=1
for j in sorted(d.values(),reverse=True):
if t==0:
ans+=j
prev=j
t+=1
rt=1
else:
if t<=44:
rt=rt*2
e=prev//2
#print(e,rt)
if j>=e:
if e*2==prev:
ans+=e
prev=e
else:
if t<=28 and e>=rt-1:
ans+=e-rt+1
prev=e
else:
break
else:
if t>44 or (rt*2-1)*j>=ans:
ans=(rt*2-1)*j
prev=j
else:
break
t+=1
print(ans)
```
No
| 53,083 | [
0.689453125,
0.1326904296875,
0.05078125,
0.2044677734375,
-0.4267578125,
-0.252197265625,
-0.498291015625,
0.292236328125,
0.1644287109375,
0.58203125,
0.595703125,
-0.340576171875,
0.1427001953125,
-0.6611328125,
-0.384033203125,
-0.2388916015625,
-0.68212890625,
-0.5546875,
-0... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Tags: brute force, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
N, M = map(int, input().split())
mar = [-1] * 26
mir = [2000] * 26
mac = [-1] * 26
mic = [2000] * 26
X = [[-1 if a == "." else ord(a)-97 for a in input()] for i in range(N)]
# print(X)
ma = -1
for i in range(N):
for j in range(M):
k = X[i][j]
if k >= 0:
mar[k] = max(mar[k], i)
mir[k] = min(mir[k], i)
mac[k] = max(mac[k], j)
mic[k] = min(mic[k], j)
ma = max(ma, k)
f = 0
ans = 1
ANS = []
for k in range(ma+1)[::-1]:
if f and mar[k] == -1 and mir[k] == 2000:
ANS.append(ANS[-1])
elif mar[k] == mir[k]:
r = mar[k]
for c in range(mic[k], mac[k]+1):
if X[r][c] < k:
ans = 0
break
else:
ANS.append((r+1, mic[k]+1, r+1, mac[k]+1))
if ans == 0:
break
f = 1
elif mac[k] == mic[k]:
c = mac[k]
for r in range(mir[k], mar[k]+1):
if X[r][c] < k:
ans = 0
break
else:
ANS.append((mir[k]+1, c+1, mar[k]+1, c+1))
if ans == 0:
break
f = 1
else:
ans = 0
break
if ans == 0:
print("NO")
else:
print("YES")
print(len(ANS))
for a in ANS[::-1]:
print(*a)
```
| 53,123 | [
0.451171875,
0.133056640625,
0.43798828125,
0.15380859375,
-0.447265625,
-0.302734375,
0.22216796875,
0.11956787109375,
-0.01837158203125,
0.77490234375,
1.3173828125,
0.2332763671875,
-0.047149658203125,
-0.48876953125,
-0.63623046875,
0.34521484375,
-0.318603515625,
-0.3764648437... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Tags: brute force, implementation
Correct Solution:
```
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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, _ = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip()
bio = sys.stdout
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main()
```
| 53,124 | [
0.451171875,
0.133056640625,
0.43798828125,
0.15380859375,
-0.447265625,
-0.302734375,
0.22216796875,
0.11956787109375,
-0.01837158203125,
0.77490234375,
1.3173828125,
0.2332763671875,
-0.047149658203125,
-0.48876953125,
-0.63623046875,
0.34521484375,
-0.318603515625,
-0.3764648437... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Tags: brute force, implementation
Correct Solution:
```
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations,groupby
import sys
import bisect
import string
import math
import time
import random
def S_():
return input()
def LS():
return [i for i in input().split()]
def I():
return int(input())
def MI():
return map(int,input().split())
def LI():
return [int(i) for i in input().split()]
def LI_():
return [int(i)-1 for i in input().split()]
def NI(n):
return [int(input()) for i in range(n)]
def NI_(n):
return [int(input())-1 for i in range(n)]
def StoI():
return [ord(i)-97 for i in input()]
def ItoS(nn):
return chr(nn+97)
def LtoS(ls):
return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
org_inp=[]
g=[[] for i in range(n)]
for i in range(E):
inp=LI()
org_inp.append(inp)
if index==0:
inp[0]-=1
inp[1]-=1
if len(inp)==2:
a,b=inp
g[a].append(b)
if not Directed:
g[b].append(a)
elif len(inp)==3:
a,b,c=inp
aa=(inp[0],inp[2])
bb=(inp[1],inp[2])
g[a].append(bb)
if not Directed:
g[b].append(aa)
return g,org_inp
def bit_combination(k,n=2):
rt=[]
for tb in range(n**k):
s=[tb//(n**bt)%n for bt in range(k)]
rt+=[s]
return rt
def show(*inp,end='\n'):
if show_flg:
print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()
def ran_input():
import random
n=random.randint(4,16)
rmin,rmax=1,10
a=[random.randint(rmin,rmax) for _ in range(n)]
return n,a
show_flg=False
show_flg=True
ans=0
t=I()
for _ in range(t):
h,w=LI()
ans=[]
t=[]
ng=False
rs=[[inf,-inf] for i in range(26)]
cs=[[inf,-inf] for i in range(26)]
for i in range(h):
s=input()
t.append(s)
for j in range(w):
if s[j]!='.':
k=ord(s[j])-97
rs[k][0]=min(rs[k][0],i+1)
rs[k][1]=max(rs[k][1],i+1)
cs[k][0]=min(cs[k][0],j+1)
cs[k][1]=max(cs[k][1],j+1)
ll=-1
for i in range(26):
if rs[i][0]!=inf:
ll=i
if ll==-1:
print('YES')
print(0)
continue
for i in range(ll+1)[::-1]:
if (rs[i][0]!=inf and rs[i][0]!=rs[i][1]) and (cs[i][0]!=inf and cs[i][0]!=cs[i][1]):
ng=True
break
else:
if rs[i][0]==inf:
ans.append(lsn)
else:
lsn=[rs[i][0],cs[i][0],rs[i][1],cs[i][1]]
ans.append(lsn)
for r in range(rs[i][0],rs[i][1]+1):
for c in range(cs[i][0],cs[i][1]+1):
#show(i,(r-1,c-1),t[r-1][c-1])
if ord(t[r-1][c-1])-97<i:
ng=True
#show(i,*rs[i],*cs[i])
if ng:
print('NO')
continue
else:
print('YES')
print(len(ans))
for i in ans[::-1]:
print(*i)
```
| 53,125 | [
0.451171875,
0.133056640625,
0.43798828125,
0.15380859375,
-0.447265625,
-0.302734375,
0.22216796875,
0.11956787109375,
-0.01837158203125,
0.77490234375,
1.3173828125,
0.2332763671875,
-0.047149658203125,
-0.48876953125,
-0.63623046875,
0.34521484375,
-0.318603515625,
-0.3764648437... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Tags: brute force, implementation
Correct Solution:
```
# I stole this code from a stupid birb
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input().rstrip() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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()
bio = sys.stdout
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main()
```
| 53,126 | [
0.451171875,
0.133056640625,
0.43798828125,
0.15380859375,
-0.447265625,
-0.302734375,
0.22216796875,
0.11956787109375,
-0.01837158203125,
0.77490234375,
1.3173828125,
0.2332763671875,
-0.047149658203125,
-0.48876953125,
-0.63623046875,
0.34521484375,
-0.318603515625,
-0.3764648437... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Tags: brute force, implementation
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
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
#-------------------------------------------------------------------------
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------------------------------------------
for _ in range (int(input())):
n,m=map(int,input().split())
a=[]
for i in range (n):
a.append(list(input()))
d=defaultdict(list)
check=[[0 for j in range (m)]for i in range (n)]
fake=[0,0,0,0]
mx=96
for ch in range (122,96,-1):
c=0
for i in range (n):
for j in range (m):
if a[i][j]==chr(ch):
#print(i,j,ch)
s=[i+1,j+1,i+1,j+1]
mx=max(mx,ch)
if fake[0]==0:
fake=s.copy()
check[i][j]=1
x=0
if i<n-1 and ord(a[i+1][j])>=ch:
k=i
while k<n-1 and ord(a[k+1][j])>=ch:
if ord(a[k+1][j])>ch and check[k+1][j]==0:
break
if ord(a[k+1][j])==ch:
x=1
k+=1
if x:
k=i
while k<n-1 and ord(a[k+1][j])>=ch:
if ord(a[k+1][j])>ch and check[k+1][j]==0:
break
k+=1
check[k][j]=1
s[2]=k+1
s[3]=j+1
if x==0 and j<m-1 and ord(a[i][j+1])>=ch:
k=j
while k<m-1 and ord(a[i][k+1])>=ch:
if ord(a[i][k+1])>ch and check[i][k+1]==0:
break
k+=1
check[i][k]=1
s[2]=i+1
s[3]=k+1
c=1
d[ch]=s
break
if c:
break
#print(check)
#print(d)
res=[]
c=1
for i in range (n):
for j in range (m):
if a[i][j]!='.' and check[i][j]==0:
c=0
break
if c==0:
break
for i in range (97,mx+1):
if len(d[i])==0:
res.append(fake)
elif len(d[i])==4:
res.append(d[i])
if c:
print("YES")
print(len(res))
for i in res:
print(*i)
else:
print("NO")
```
| 53,127 | [
0.451171875,
0.133056640625,
0.43798828125,
0.15380859375,
-0.447265625,
-0.302734375,
0.22216796875,
0.11956787109375,
-0.01837158203125,
0.77490234375,
1.3173828125,
0.2332763671875,
-0.047149658203125,
-0.48876953125,
-0.63623046875,
0.34521484375,
-0.318603515625,
-0.3764648437... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Tags: brute force, implementation
Correct Solution:
```
import sys, io
inp = io.BytesIO(sys.stdin.buffer.read())
input = lambda: inp.readline().rstrip().decode('ascii')
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
main()
```
| 53,128 | [
0.451171875,
0.133056640625,
0.43798828125,
0.15380859375,
-0.447265625,
-0.302734375,
0.22216796875,
0.11956787109375,
-0.01837158203125,
0.77490234375,
1.3173828125,
0.2332763671875,
-0.047149658203125,
-0.48876953125,
-0.63623046875,
0.34521484375,
-0.318603515625,
-0.3764648437... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Tags: brute force, implementation
Correct Solution:
```
import sys
#sys.stdin = open('inE', 'r')
t = int(input())
for ti in range(t):
n,m = map(int, input().split())
a = []
for i in range(n):
a.append(input())
top = {}
bot = {}
l = {}
r = {}
res = True
for y in range(n):
for x in range(m):
c = a[y][x]
if c != '.':
if c not in top:
top[c] = y
bot[c] = y
l[c] = x
r[c] = x
else:
if top[c] == y:
r[c] = x
xi = x - 1
while xi >= 0 and a[y][xi] != c:
if a[y][xi] == '.' or a[y][xi] < c:
res = False
xi -= 1
elif l[c] == x and r[c] == x:
bot[c] = y
yi = y - 1
while yi >= 0 and a[yi][x] != c:
if a[yi][x] == '.' or a[yi][x] < c:
res = False
yi -= 1
else:
res = False
if len(top) == 0:
sys.stdout.write('YES\n')
sys.stdout.write('0\n')
elif res:
mxc = max(top)
cnt = ord(mxc) & 31
sys.stdout.write('YES\n')
sys.stdout.write(str(cnt)+'\n')
for i in range(cnt):
ci = chr(ord('a') + i)
if ci not in top:
ci = mxc
sys.stdout.write(f'{top[ci]+1} {l[ci]+1} {bot[ci]+1} {r[ci]+1}\n')
else:
sys.stdout.write('NO\n')
```
| 53,129 | [
0.451171875,
0.133056640625,
0.43798828125,
0.15380859375,
-0.447265625,
-0.302734375,
0.22216796875,
0.11956787109375,
-0.01837158203125,
0.77490234375,
1.3173828125,
0.2332763671875,
-0.047149658203125,
-0.48876953125,
-0.63623046875,
0.34521484375,
-0.318603515625,
-0.3764648437... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Tags: brute force, implementation
Correct Solution:
```
import sys
def solve():
H, W = map(int, sys.stdin.readline().split())
G = [[ord(s) - 46 for s in sys.stdin.readline().strip()] for _ in range(H)]
k = 0
inf = 10**9
Stbw = [-inf]*77
Stsw = [inf]*77
Stbh = [-inf]*77
Stsh = [inf]*77
for h, G1 in enumerate(G, 1):
k = max(k, max(G1))
for w, g in enumerate(G1, 1):
if not g:
continue
Stbw[g] = max(Stbw[g], w)
Stsw[g] = min(Stsw[g], w)
Stbh[g] = max(Stbh[g], h)
Stsh[g] = min(Stsh[g], h)
if k == 0:
return []
A = []
for j in range(k, 50, -1):
if Stbw[j] == -inf and Stbh[j] == -inf:
A.append(A[-1])
continue
bw = (Stbw[j] == Stsw[j])
bh = (Stbh[j] == Stsh[j])
if not bw and not bh:
return False
if bw:
w = Stbw[j]- 1
for h in range(Stsh[j]-1, Stbh[j]):
if G[h][w] < j:
return False
elif bh:
h = Stbh[j]- 1
for w in range(Stsw[j]-1, Stbw[j]):
if G[h][w] < j:
return False
A.append((Stsh[j], Stsw[j], Stbh[j], Stbw[j]))
return A[::-1]
if __name__ == '__main__':
T = int(input())
for _ in range(T):
ans = solve()
if ans is False:
print('NO')
continue
print('YES')
print(len(ans))
for a in ans:
print(*a)
```
| 53,130 | [
0.451171875,
0.133056640625,
0.43798828125,
0.15380859375,
-0.447265625,
-0.302734375,
0.22216796875,
0.11956787109375,
-0.01837158203125,
0.77490234375,
1.3173828125,
0.2332763671875,
-0.047149658203125,
-0.48876953125,
-0.63623046875,
0.34521484375,
-0.318603515625,
-0.3764648437... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
import sys
input = sys.stdin.readline
def solve():
H, W = map(int, input().split())
G = [[ord(s) - 46 for s in input().strip()] for _ in range(H)]
Gy = list(map(list, zip(*G)))
k = 0
St = [None]*77
for h, G1 in enumerate(G, 1):
k = max(k, max(G1))
for w, g in enumerate(G1, 1):
if not g:
continue
if St[g] is None:
St[g] = (h, w)
elif type(St[g]) == tuple:
h1, w1 = St[g]
if h == h1:
St[g] = h
elif w == w1:
St[g] = -w
else:
return False
else:
if St[g] == h or St[g] == -w:
continue
return False
if k == 0:
return []
A = []
for j in range(k, 50, -1):
if St[j] is None:
A.append(A[-1])
continue
if type(St[j]) == tuple:
A.append(St[j]*2)
continue
x = St[j]
if x > 0:
Gh = G[x-1]
p = None
e = None
for ig, g in enumerate(Gh):
if g == j:
p = ig
break
for ig, g in enumerate(Gh[::-1]):
ig = W - 1 - ig
if g == j:
e = ig
break
for ig in range(p, e + 1):
if Gh[ig] < j:
return False
A.append((x, p+1, x, e+1))
else:
Gw = Gy[-x-1]
p = None
e = None
for ig, g in enumerate(Gw):
if g == j:
p = ig
break
for ig, g in enumerate(Gw[::-1]):
ig = H - 1 - ig
if g == j:
e = ig
break
for ig in range(p, e + 1):
if Gw[ig] < j:
return False
A.append((p+1, -x, e+1, -x))
return A[::-1]
if __name__ == '__main__':
T = int(input())
for _ in range(T):
ans = solve()
if ans is False:
print('NO')
continue
print('YES')
print(len(ans))
for a in ans:
print(*a)
```
Yes
| 53,131 | [
0.56201171875,
0.15576171875,
0.369384765625,
0.09759521484375,
-0.50439453125,
-0.2822265625,
0.09942626953125,
0.166259765625,
-0.0004754066467285156,
0.74658203125,
1.1728515625,
0.1961669921875,
0.0091400146484375,
-0.5625,
-0.65185546875,
0.1568603515625,
-0.29248046875,
-0.35... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
def naiveSolve():
return
from collections import defaultdict
def main():
t=int(input())
allans=[]
for _ in range(t):
# n=2000
# m=2000
# grid=['a'*m]*m
n,m=readIntArr()
grid=[]
for __ in range(n):
grid.append(input())
ok=True
snakes=defaultdict(lambda:[]) # {'a':[coords]}
for i in range(n):
for j in range(m):
if grid[i][j]!='.':
snakes[grid[i][j]].append([i,j])
l=len(snakes[grid[i][j]])
if l>max(n,m): # to prevent MLE
ok=False
break
if ok==False:
break
if ok==False:
allans.append(['NO'])
continue
startEnd=dict() # {'a':[start coord, end coord]}
# check that snake is straight
for letter,coords in snakes.items():
if len(coords)>=2:
if coords[0][0]==coords[1][0]: # horizontal
for i in range(2,len(coords)):
if coords[0][0]!=coords[i][0]:
ok=False
break
elif coords[0][1]==coords[1][1]: # vertical
for i in range(2,len(coords)):
if coords[0][1]!=coords[i][1]:
ok=False
break
else: # diagonal. wrong
ok=False
if ok==False: break
startEnd[letter]=[coords[0],coords[-1]]
if ok==False:
allans.append(['NO'])
continue
# created adjacency dict for topological sort
adj=defaultdict(lambda:[])
for letter,[start,end] in startEnd.items():
if start[0]==end[0]: # horizontal
for col in range(start[1],end[1]+1):
letter2=grid[start[0]][col]
if letter!=letter2:
if letter2=='.': # broken snake
ok=False
else:
adj[letter].append(letter2)
else: # vertical
for row in range(start[0],end[0]+1):
letter2=grid[row][start[1]]
if letter!=letter2:
if letter2=='.': # broken snake
ok=False
else:
adj[letter].append(letter2)
if ok==False:
allans.append(['NO'])
continue
# # check adj for cycles
chars=startEnd.keys()
# v=set()
# for c in chars:
# if c in v: continue
# v.add(c)
# path={c}
# stack=[c]
# while stack:
# c=stack.pop()
# for nex in adj[c]:
# if nex in path: # has cycle
# ok=False
# break
# else:
# path.add(c)
# if c not in v:
# v.add(c)
# stack.append(c)
# if ok==False: # cycle detected
# allans.append(['NO'])
# continue
# # run topological sort
# order=[]
# v=set()
# def dfs(c):
# for nex in adj[c]:
# if nex not in v:
# v.add(nex)
# dfs(nex)
# order.append(c)
# for c in chars:
# if c not in v:
# v.add(c)
# dfs(c)
# order.reverse()
# I just realised that he has to write in order a,b,c...
# check that adj does not contradict order
for u in chars:
for v in adj[u]:
if v<u:
ok=False
if ok==False: # cycle detected
allans.append(['NO'])
continue
order=sorted(chars)
allans.append(['YES'])
if len(order)==0:
allans.append([0])
else:
allC='abcdefghijklmnopqrstuvwxyz'
maxChar=order[-1]
maxCharIdx=allC.index(maxChar)
allans.append([maxCharIdx+1])
dr,dc=startEnd[order[-1]][0] # dummy row and column to put other snakes
dr+=1; dc+=1
for i in range(maxCharIdx+1):
if allC[i] not in order: # the other chars < maxChar that are not in grid
allans.append([dr,dc,dr,dc])
else:
[r1,c1],[r2,c2]=startEnd[allC[i]]
r1+=1; c1+=1; r2+=1; c2+=1
allans.append([r1,c1,r2,c2])
multiLineArrayOfArraysPrint(allans)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(l,r):
print('? {} {}'.format(l,r))
sys.stdout.flush()
return int(input())
def answerInteractive(x):
print('! {}'.format(x))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
```
Yes
| 53,132 | [
0.56201171875,
0.15576171875,
0.369384765625,
0.09759521484375,
-0.50439453125,
-0.2822265625,
0.09942626953125,
0.166259765625,
-0.0004754066467285156,
0.74658203125,
1.1728515625,
0.1961669921875,
0.0091400146484375,
-0.5625,
-0.65185546875,
0.1568603515625,
-0.29248046875,
-0.35... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(object):
newlines = 0
def __init__(self, file):
self.stream = BytesIO()
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = self.stream.write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.stream.seek((self.stream.tell(), self.stream.seek(0,2), self.stream.write(s))[0])
return s
def read(self):
while self._fill(): pass
return self.stream.read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return self.stream.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.stream.getvalue())
self.stream.truncate(0), self.stream.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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()
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main()
```
Yes
| 53,133 | [
0.56201171875,
0.15576171875,
0.369384765625,
0.09759521484375,
-0.50439453125,
-0.2822265625,
0.09942626953125,
0.166259765625,
-0.0004754066467285156,
0.74658203125,
1.1728515625,
0.1961669921875,
0.0091400146484375,
-0.5625,
-0.65185546875,
0.1568603515625,
-0.29248046875,
-0.35... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
from sys import stdin, stdout
from collections import defaultdict
def process():
let_to_squares = defaultdict(list)
square_to_lets = defaultdict(list)
n, m = map(int, stdin.readline().split())
grid = []
for i in range(n):
row = stdin.readline().strip()
grid.append([c for c in row])
max_let = 0
for i in range(n):
for j in range(m):
let = grid[i][j]
if let == '.':
continue
max_let = max(ord(let), max_let)
let_to_squares[let].append((i, j))
# print(let_to_squares)
if max_let == 0:
stdout.write("YES\n0\n")
return
for i in range(n):
for j in range(m):
if ord(grid[i][j]) == max_let:
any_square = [i+1, j+1, i+1, j+1]
remaining = defaultdict(int)
coords = {}
for let in let_to_squares.keys():
row_min = n+1
col_min = m+1
row_max = -1
col_max = -1
for i, j in let_to_squares[let]:
row_min = min(row_min, i)
row_max = max(row_max, i)
col_min = min(col_min, j)
col_max = max(col_max, j)
coords[let] = [row_min+1, col_min+1, row_max+1, col_max+1]
if row_min != row_max and col_min != col_max:
stdout.write("NO\n")
return
for i in range(row_min, row_max+1):
for j in range(col_min, col_max+1):
if grid[i][j] != let:
if grid[i][j] == '.':
stdout.write("NO\n")
return
remaining[let] += 1
square_to_lets[(i, j)].append(let)
for let in range(max_let, ord('a')-1, -1):
if remaining[chr(let)] != 0:
stdout.write("NO\n")
return
for i,j in let_to_squares[chr(let)]:
for new_let in square_to_lets[(i, j)]:
remaining[new_let] -= 1
stdout.write("YES\n")
stdout.write(str(max_let-ord('a')+1) + "\n")
for let in range(ord('a'), max_let+1):
if chr(let) in coords:
t = coords[chr(let)]
else:
t = any_square
stdout.write(' '.join(map(str, t)) + "\n")
t = int(stdin.readline())
for it in range(t):
process()
```
Yes
| 53,134 | [
0.56201171875,
0.15576171875,
0.369384765625,
0.09759521484375,
-0.50439453125,
-0.2822265625,
0.09942626953125,
0.166259765625,
-0.0004754066467285156,
0.74658203125,
1.1728515625,
0.1961669921875,
0.0091400146484375,
-0.5625,
-0.65185546875,
0.1568603515625,
-0.29248046875,
-0.35... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
mat=[]
final_mat=[]
for i in range(n):
l=list(input())
w=['.']*m
final_mat.append(w)
mat.append(l)
dic=dict()
flag=False
for i in range(n):
for j in range(m):
if mat[i][j]!='.':
flag=True
if mat[i][j] in dic:
dic[mat[i][j]].append([i,j])
else:
dic[mat[i][j]]=[[i,j]]
for k in dic.keys():
dic[k]=sorted(dic[k])
if flag:
# print(dic)
flag=True
for k in dic.keys():
setx=set()
sety=set()
for w in dic[k]:
setx.add(w[0])
sety.add(w[1])
if len(setx)==1 or len(sety)==1:
flag=True
else:
flag=False
break
final_mat[dic[k][0][0]][dic[k][0][1]]=k
final_mat[dic[k][-1][0]][dic[k][-1][1]]=k
if flag==False:
print('NO')
else:
ans=dict()
li=['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a']
f=1
main='-1'
count=0
for i in li:
if i in dic:
if f==1:
f=0
main=i
x=dic[i][0][0]
y=dic[i][0][1]
xend=dic[i][-1][0]
yend=dic[i][-1][1]
if x==xend:
for j in range(y,yend+1):
if final_mat[x][j]=='.':
final_mat[x][j]=i
elif y==yend:
for j in range(x,xend+1):
if final_mat[j][y]=='.':
final_mat[j][y]=i
ans[i]=i
else:
if main!='-1':
ans[i]=main
#print(final_mat)
flag=True
for i in range(n):
for j in range(m):
if mat[i][j]==final_mat[i][j]:
pass
else:
flag=False
if flag==False:
break
if flag==False:
print('NO')
else:
print('YES')
print(26-li.index(main))
for i in li[::-1]:
# print('in',i)
if i in ans:
print(dic[ans[i]][0][0]+1,dic[ans[i]][0][1]+1,dic[ans[i]][-1][0]+1,dic[ans[i]][-1][1]+1)
else:
break
else:
print('YES')
print('0')
```
No
| 53,135 | [
0.56201171875,
0.15576171875,
0.369384765625,
0.09759521484375,
-0.50439453125,
-0.2822265625,
0.09942626953125,
0.166259765625,
-0.0004754066467285156,
0.74658203125,
1.1728515625,
0.1961669921875,
0.0091400146484375,
-0.5625,
-0.65185546875,
0.1568603515625,
-0.29248046875,
-0.35... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
# sys.setrecursionlimit(200000)
# mod = 10**9+7
# mod = 998244353
decimal.getcontext().prec = 46
def primeFactors(n):
prime = set()
while n % 2 == 0:
prime.add(2)
n = n//2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
prime.add(i)
n = n//i
if n > 2:
prime.add(n)
return list(prime)
def getFactors(n) :
factors = []
i = 1
while i <= math.sqrt(n):
if (n % i == 0) :
if (n // i == i) :
factors.append(i)
else :
factors.append(i)
factors.append(n//i)
i = i + 1
return factors
def modefiedSieve():
mx=10**7+1
sieve=[-1]*mx
for i in range(2,mx):
if sieve[i]==-1:
sieve[i]=i
for j in range(i*i,mx,i):
if sieve[j]==-1:
sieve[j]=i
return sieve
def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
num = []
for p in range(2, n+1):
if prime[p]:
num.append(p)
return num
def lcm(a,b):
return (a*b)//math.gcd(a,b)
def sort_dict(key_value):
return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))
def list_input():
return list(map(int,input().split()))
def num_input():
return map(int,input().split())
def string_list():
return list(input())
def decimalToBinary(n):
return bin(n).replace("0b", "")
def binaryToDecimal(n):
return int(n,2)
def DFS(n,s,adj):
visited = [False for i in range(n+1)]
stack = []
stack.append(s)
while (len(stack)):
s = stack[-1]
stack.pop()
if (not visited[s]):
visited[s] = True
for node in adj[s]:
if (not visited[node]):
stack.append(node)
def maxSubArraySum(a,size):
maxint = 10**10
max_so_far = -maxint - 1
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
def find_snake(i,j,mat,n,m):
symbol = mat[i][j]
mat[i][j] = '.'
col = j+1
flag = False
while col < m:
if mat[i][col] == '.' or ord(mat[i][col]) < ord(symbol):
break
elif mat[i][col] == symbol:
flag = True
mat[i][col] = '.'
col += 1
if not(flag):
row = i+1
while row < n:
if mat[row][j] == '.' or ord(mat[row][j]) < ord(symbol):
break
elif mat[row][j] == symbol:
if j-1 >= 0 and j+1 < m and (mat[row][j-1] != '.' and mat[row][j+1] != '.'):
if mat[row][j-1] == mat[row][j+1] and ord(mat[row][j-1]) < ord(symbol):
mat[row][j] = mat[row][j-1]
else:
left_elements = set(mat[row][:j])
right_elements = set(mat[row][j+1:])
both_side_present = sorted(list(left_elements.intersection(right_elements)))
if '.' in both_side_present:
both_side_present.pop(0)
if both_side_present == []:
mat[row][j] = '.'
else:
mat[row][j] = both_side_present[0]
else:
mat[row][j] = '.'
row += 1
if flag:
return (i+1,col)
return (row,j+1)
def solve():
n,m = num_input()
mat = []
for _ in range(n):
mat.append(list(input()))
visited = []
ans = {}
for i in range(n):
for j in range(m):
if mat[i][j] != '.':
if mat[i][j] in visited:
print('NO')
return
else:
visited.append(mat[i][j])
symbol = mat[i][j]
start = (i+1,j+1)
end = find_snake(i,j,mat,n,m)
if end == -1:
print('NO')
return
ans[symbol] = (start,end)
print('YES')
final = []
arr = sorted(list(ans.keys()))
for i in range(26):
if arr == []:
break
if chr(ord('a')+i) == arr[0]:
(x,y),(u,v) = ans[arr[0]]
final.append([x,y,u,v])
arr.pop(0)
else:
(x,y),(u,v) = ans[arr[-1]]
final.append([x,y,u,v])
print(len(final))
for i in final:
print(*i)
t = 1
t = int(input())
for _ in range(t):
solve()
```
No
| 53,136 | [
0.56201171875,
0.15576171875,
0.369384765625,
0.09759521484375,
-0.50439453125,
-0.2822265625,
0.09942626953125,
0.166259765625,
-0.0004754066467285156,
0.74658203125,
1.1728515625,
0.1961669921875,
0.0091400146484375,
-0.5625,
-0.65185546875,
0.1568603515625,
-0.29248046875,
-0.35... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
def mp():
return map(int, input().split())
t = int(input())
for tt in range(t):
n, m = mp()
s = [[j for j in input()] for i in range(n)]
ver = [[0] * 26 for i in range(m + 1)]
hor = [[0] * 26 for i in range(n + 1)]
max_hor = [-1] * 26
max_ver = [-1] * 26
for i in range(n):
for j in range(m):
if s[i][j] != '.':
c = ord(s[i][j]) - 97
hor[i][c] += 1
ver[j][c] += 1
if hor[i][c] > hor[max_hor[c]][c]:
max_hor[c] = i
if ver[j][c] > ver[max_ver[c]][c]:
max_ver[c] = j
ans = [0] * 26
qi = qj = -1
for k in range(25, -1, -1):
if max_hor[k] != -1 and max_ver[k] != -1:
i, j = max_hor[k], max_ver[k]
old_i, old_j = i, j
while i < n and j < m and (ord(s[i][j]) == 97 + k or s[i][j] == '?'):
s[i][j] = '?'
qi, qj = i, j
if hor[i][k] > ver[j][k]:
j += 1
else:
i += 1
if i == old_i:
ans[k] = (old_i + 1, old_j + 1, i + 1, j)
else:
ans[k] = (old_i + 1, old_j + 1, i, j + 1)
fail = False
for i in range(n):
for j in range(m):
if not s[i][j] in ['.', '?']:
fail = True
if fail:
print('NO')
else:
print('YES')
print(len(ans) - ans.count(0))
before = (ans.count(0) != 26)
for i in range(26):
if ans[i] != 0:
print(*ans[i])
before = False
elif before:
print(qi + 1, qj + 1, qi + 1, qj + 1)
```
No
| 53,137 | [
0.56201171875,
0.15576171875,
0.369384765625,
0.09759521484375,
-0.50439453125,
-0.2822265625,
0.09942626953125,
0.166259765625,
-0.0004754066467285156,
0.74658203125,
1.1728515625,
0.1961669921875,
0.0091400146484375,
-0.5625,
-0.65185546875,
0.1568603515625,
-0.29248046875,
-0.35... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.
The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.
Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.
It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.
Output
Print the answer for each test case in the input.
In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.
If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.
Note that Polycarp starts drawing of snakes with an empty sheet of paper.
Examples
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..
Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5
Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..
Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO
Input
2
3 3
...
.a.
...
2 2
bb
cc
Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2
Submitted Solution:
```
import string
t = int(input())
for test_case in range(t):
n, m = [int(_) for _ in input().split()]
board = [input() for _ in range(n)]
snakes = {}
for i, row in enumerate(board):
for j, l in enumerate(row):
if l != '.':
if l not in snakes:
snakes[l] = (i, i, j, j)
else:
snakes[l] = (min(snakes[l][0], i), max(snakes[l][1], i), min(snakes[l][2], j), max(snakes[l][3], j))
valid = True
for _, (r1, r2, c1, c2) in snakes.items():
if r1 != r2 and c1 != c2:
valid = False
if not valid:
print('NO')
continue
for i, row in enumerate(board):
for j, l in enumerate(row):
if l != '.':
for s, (r1, r2, c1, c2) in snakes.items():
if r1 <= i and i <= r2 and c1 <= j and j <= c2:
if l < s:
valid = False
if valid:
print('YES')
if snakes:
max_letter = max(snakes.keys())
k = string.ascii_lowercase.find(max_letter) + 1
print(k)
for i in range(k):
l = string.ascii_lowercase[i]
if l in snakes:
print(' '.join([str(snakes[l][0] + 1), str(snakes[l][2] + 1), str(snakes[l][1] + 1), str(snakes[l][3] + 1)]))
else:
print(' '.join([str(snakes[max_letter][0] + 1), str(snakes[max_letter][2] + 1), str(snakes[max_letter][1] + 1), str(snakes[max_letter][3] + 1)]))
else:
print(0)
else:
print('NO')
```
No
| 53,138 | [
0.56201171875,
0.15576171875,
0.369384765625,
0.09759521484375,
-0.50439453125,
-0.2822265625,
0.09942626953125,
0.166259765625,
-0.0004754066467285156,
0.74658203125,
1.1728515625,
0.1961669921875,
0.0091400146484375,
-0.5625,
-0.65185546875,
0.1568603515625,
-0.29248046875,
-0.35... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.
He sent to the coordinator a set of n problems. Each problem has it's quality, the quality of the i-th problem is ai (ai can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index 1, the hardest problem has index n.
The coordinator's mood is equal to q now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality b, the value b is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems.
If after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset.
Polycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has m guesses "the current coordinator's mood q = bi".
For each of m guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to 0 while he reads problems from the easiest of the remaining problems to the hardest.
Input
The first line of input contains two integers n and m (1 ≤ n ≤ 750, 1 ≤ m ≤ 200 000) — the number of problems in the problemset and the number of guesses about the current coordinator's mood.
The second line of input contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the qualities of the problems in order of increasing difficulty.
The third line of input contains m integers b1, b2, ..., bm (0 ≤ bi ≤ 1015) — the guesses of the current coordinator's mood q.
Output
Print m lines, in i-th line print single integer — the answer to the problem with q = bi.
Example
Input
6 3
8 -5 -4 1 -7 4
0 7 3
Output
2
0
1
Submitted Solution:
```
#!/usr/bin/env python3
import sys
from collections import namedtuple
from itertools import accumulate
#Rango = namedtuple('Rango', ['desde', 'hasta'])
n,m= tuple(map(int, input().split()))
lista = list(map(int, input().split()))
mood = list(map(int, input().split()))
acumulada = list(accumulate(lista))
#rangos =[Rango(desde= - min(acumulada),hasta=sys.maxsize)]
#print("acumulada=",acumulada)
rangos=[]
minimau =0
for i in acumulada:
if (i<0 and i<minimau):
minimau=i
rangos.append(-i)
rangos.append(sys.maxsize)
#print("rangos=",rangos)
tam = len(rangos)-1
#print(mood)
for i in mood:
for k,j in enumerate(rangos):
if i<j:
print(tam-k)
break
```
No
| 53,535 | [
0.469970703125,
0.1422119140625,
0.0309906005859375,
-0.08056640625,
-0.63671875,
-0.365966796875,
-0.2529296875,
0.2147216796875,
-0.2022705078125,
0.537109375,
0.5244140625,
-0.376220703125,
-0.27099609375,
-0.79638671875,
-0.17431640625,
-0.51318359375,
-0.77783203125,
-0.316650... | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.