message stringlengths 2 43.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 853 107k | cluster float64 24 24 | __index_level_0__ int64 1.71k 214k |
|---|---|---|---|---|---|
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]. | instruction | 0 | 49,909 | 24 | 99,818 |
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)
``` | output | 1 | 49,909 | 24 | 99,819 |
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]. | instruction | 0 | 49,910 | 24 | 99,820 |
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())):
``` | output | 1 | 49,910 | 24 | 99,821 |
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]. | instruction | 0 | 49,911 | 24 | 99,822 |
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)
``` | output | 1 | 49,911 | 24 | 99,823 |
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]. | instruction | 0 | 49,912 | 24 | 99,824 |
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)
``` | output | 1 | 49,912 | 24 | 99,825 |
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]. | instruction | 0 | 49,913 | 24 | 99,826 |
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}')
``` | output | 1 | 49,913 | 24 | 99,827 |
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]. | instruction | 0 | 49,914 | 24 | 99,828 |
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)
``` | output | 1 | 49,914 | 24 | 99,829 |
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]. | instruction | 0 | 49,915 | 24 | 99,830 |
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())
``` | output | 1 | 49,915 | 24 | 99,831 |
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)
``` | instruction | 0 | 49,916 | 24 | 99,832 |
Yes | output | 1 | 49,916 | 24 | 99,833 |
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()
``` | instruction | 0 | 49,917 | 24 | 99,834 |
Yes | output | 1 | 49,917 | 24 | 99,835 |
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)
``` | instruction | 0 | 49,918 | 24 | 99,836 |
Yes | output | 1 | 49,918 | 24 | 99,837 |
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()
``` | instruction | 0 | 49,919 | 24 | 99,838 |
Yes | output | 1 | 49,919 | 24 | 99,839 |
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)
``` | instruction | 0 | 49,920 | 24 | 99,840 |
No | output | 1 | 49,920 | 24 | 99,841 |
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)
``` | instruction | 0 | 49,921 | 24 | 99,842 |
No | output | 1 | 49,921 | 24 | 99,843 |
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
'''
``` | instruction | 0 | 49,922 | 24 | 99,844 |
No | output | 1 | 49,922 | 24 | 99,845 |
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()))
``` | instruction | 0 | 49,923 | 24 | 99,846 |
No | output | 1 | 49,923 | 24 | 99,847 |
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. | instruction | 0 | 49,960 | 24 | 99,920 |
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)
``` | output | 1 | 49,960 | 24 | 99,921 |
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. | instruction | 0 | 49,961 | 24 | 99,922 |
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)
``` | output | 1 | 49,961 | 24 | 99,923 |
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. | instruction | 0 | 49,962 | 24 | 99,924 |
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)
``` | output | 1 | 49,962 | 24 | 99,925 |
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. | instruction | 0 | 49,963 | 24 | 99,926 |
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)
``` | output | 1 | 49,963 | 24 | 99,927 |
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. | instruction | 0 | 49,964 | 24 | 99,928 |
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)
``` | output | 1 | 49,964 | 24 | 99,929 |
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. | instruction | 0 | 49,965 | 24 | 99,930 |
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()
``` | output | 1 | 49,965 | 24 | 99,931 |
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. | instruction | 0 | 49,966 | 24 | 99,932 |
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)
``` | output | 1 | 49,966 | 24 | 99,933 |
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. | instruction | 0 | 49,967 | 24 | 99,934 |
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)
``` | output | 1 | 49,967 | 24 | 99,935 |
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)
``` | instruction | 0 | 49,968 | 24 | 99,936 |
Yes | output | 1 | 49,968 | 24 | 99,937 |
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)
``` | instruction | 0 | 49,969 | 24 | 99,938 |
Yes | output | 1 | 49,969 | 24 | 99,939 |
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
``` | instruction | 0 | 49,970 | 24 | 99,940 |
Yes | output | 1 | 49,970 | 24 | 99,941 |
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)
``` | instruction | 0 | 49,971 | 24 | 99,942 |
Yes | output | 1 | 49,971 | 24 | 99,943 |
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)
``` | instruction | 0 | 49,972 | 24 | 99,944 |
No | output | 1 | 49,972 | 24 | 99,945 |
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)
``` | instruction | 0 | 49,973 | 24 | 99,946 |
No | output | 1 | 49,973 | 24 | 99,947 |
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)
``` | instruction | 0 | 49,974 | 24 | 99,948 |
No | output | 1 | 49,974 | 24 | 99,949 |
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)
``` | instruction | 0 | 49,975 | 24 | 99,950 |
No | output | 1 | 49,975 | 24 | 99,951 |
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. | instruction | 0 | 50,233 | 24 | 100,466 |
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)
``` | output | 1 | 50,233 | 24 | 100,467 |
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. | instruction | 0 | 50,234 | 24 | 100,468 |
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()
``` | output | 1 | 50,234 | 24 | 100,469 |
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. | instruction | 0 | 50,235 | 24 | 100,470 |
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)
``` | output | 1 | 50,235 | 24 | 100,471 |
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. | instruction | 0 | 50,236 | 24 | 100,472 |
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)
``` | output | 1 | 50,236 | 24 | 100,473 |
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. | instruction | 0 | 50,237 | 24 | 100,474 |
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))
``` | output | 1 | 50,237 | 24 | 100,475 |
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. | instruction | 0 | 50,238 | 24 | 100,476 |
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
'''
``` | output | 1 | 50,238 | 24 | 100,477 |
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. | instruction | 0 | 50,239 | 24 | 100,478 |
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()
``` | output | 1 | 50,239 | 24 | 100,479 |
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. | instruction | 0 | 50,240 | 24 | 100,480 |
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)
``` | output | 1 | 50,240 | 24 | 100,481 |
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))
``` | instruction | 0 | 50,241 | 24 | 100,482 |
Yes | output | 1 | 50,241 | 24 | 100,483 |
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))
``` | instruction | 0 | 50,242 | 24 | 100,484 |
Yes | output | 1 | 50,242 | 24 | 100,485 |
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)
``` | instruction | 0 | 50,243 | 24 | 100,486 |
Yes | output | 1 | 50,243 | 24 | 100,487 |
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)
``` | instruction | 0 | 50,244 | 24 | 100,488 |
Yes | output | 1 | 50,244 | 24 | 100,489 |
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)
``` | instruction | 0 | 50,245 | 24 | 100,490 |
No | output | 1 | 50,245 | 24 | 100,491 |
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)
``` | instruction | 0 | 50,246 | 24 | 100,492 |
No | output | 1 | 50,246 | 24 | 100,493 |
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)
``` | instruction | 0 | 50,247 | 24 | 100,494 |
No | output | 1 | 50,247 | 24 | 100,495 |
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)
``` | instruction | 0 | 50,248 | 24 | 100,496 |
No | output | 1 | 50,248 | 24 | 100,497 |
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). | instruction | 0 | 50,655 | 24 | 101,310 |
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)
``` | output | 1 | 50,655 | 24 | 101,311 |
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). | instruction | 0 | 50,656 | 24 | 101,312 |
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)
``` | output | 1 | 50,656 | 24 | 101,313 |
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). | instruction | 0 | 50,657 | 24 | 101,314 |
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)
``` | output | 1 | 50,657 | 24 | 101,315 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.