message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
An army of n droids is lined up in one row. Each droid is described by m integers a1, a2, ..., am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it).
A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?
Input
The first line contains three integers n, m, k (1 ≤ n ≤ 105, 1 ≤ m ≤ 5, 0 ≤ k ≤ 109) — the number of droids, the number of detail types and the number of available shots, respectively.
Next n lines follow describing the droids. Each line contains m integers a1, a2, ..., am (0 ≤ ai ≤ 108), where ai is the number of details of the i-th type for the respective robot.
Output
Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.
If there are multiple optimal solutions, print any of them.
It is not necessary to make exactly k shots, the number of shots can be less.
Examples
Input
5 2 4
4 0
1 2
2 1
0 2
1 3
Output
2 2
Input
3 2 4
1 2
1 3
2 2
Output
1 3
Note
In the first test the second, third and fourth droids will be destroyed.
In the second test the first and second droids will be destroyed. | instruction | 0 | 76,254 | 14 | 152,508 |
Tags: binary search, data structures, two pointers
Correct Solution:
```
#!/usr/bin/env python
# coding=utf-8
n, m, k = map(int, input().split())
mCnt = 0;
ans = [0] * m;
start = 0
end = 0
Q = [[] for i in range(m)]
for i in range(n):
A = list(map(int, input().split()))
z = 0
for j in range(m):
while Q[j] and Q[j][-1][0] < A[j]:
Q[j].pop()
Q[j].append([A[j], i])
z += Q[j][0][0]
if z <= k:
end = i + 1
if mCnt < end - start:
mCnt = end - start
for j in range(m):
ans[j] = Q[j][0][0]
else:
while True:
z = 0
for j in range(m):
if Q[j] and Q[j][0][1] == start:
Q[j].pop(0)
if Q[j]: z += Q[j][0][0]
start += 1
if z <= k : break;
end += 1
for i in ans:
print(i, end = " ")
``` | output | 1 | 76,254 | 14 | 152,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An army of n droids is lined up in one row. Each droid is described by m integers a1, a2, ..., am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it).
A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?
Input
The first line contains three integers n, m, k (1 ≤ n ≤ 105, 1 ≤ m ≤ 5, 0 ≤ k ≤ 109) — the number of droids, the number of detail types and the number of available shots, respectively.
Next n lines follow describing the droids. Each line contains m integers a1, a2, ..., am (0 ≤ ai ≤ 108), where ai is the number of details of the i-th type for the respective robot.
Output
Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.
If there are multiple optimal solutions, print any of them.
It is not necessary to make exactly k shots, the number of shots can be less.
Examples
Input
5 2 4
4 0
1 2
2 1
0 2
1 3
Output
2 2
Input
3 2 4
1 2
1 3
2 2
Output
1 3
Note
In the first test the second, third and fourth droids will be destroyed.
In the second test the first and second droids will be destroyed. | instruction | 0 | 76,255 | 14 | 152,510 |
Tags: binary search, data structures, two pointers
Correct Solution:
```
n,m,k=map(int,input().split())
q=0
rez=[0]*int(m)
st=0
end=0
p=[[] for i in range(int(m))]
for i in range(int(n)):
a=list(map(int,input().split()))
c=0
for ii in range(m):
while p[ii] and p[ii][-1][0]<a[ii]:
p[ii].pop()
p[ii].append([a[ii],i])
c+=p[ii][0][0]
if c<=k:
end=i+1
if q<end-st:
q=end-st
for iii in range(m):
rez[iii]=p[iii][0][0]
else:
while 1==1:
c=0
for j in range(m):
if p[j] and p[j][0][1]==st:
p[j].pop(0)
if p[j]:c+=p[j][0][0]
st+=1
if c<=k:
break
end+=1
for i in rez:
print(i,end= " ")
``` | output | 1 | 76,255 | 14 | 152,511 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An army of n droids is lined up in one row. Each droid is described by m integers a1, a2, ..., am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it).
A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?
Input
The first line contains three integers n, m, k (1 ≤ n ≤ 105, 1 ≤ m ≤ 5, 0 ≤ k ≤ 109) — the number of droids, the number of detail types and the number of available shots, respectively.
Next n lines follow describing the droids. Each line contains m integers a1, a2, ..., am (0 ≤ ai ≤ 108), where ai is the number of details of the i-th type for the respective robot.
Output
Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.
If there are multiple optimal solutions, print any of them.
It is not necessary to make exactly k shots, the number of shots can be less.
Examples
Input
5 2 4
4 0
1 2
2 1
0 2
1 3
Output
2 2
Input
3 2 4
1 2
1 3
2 2
Output
1 3
Note
In the first test the second, third and fourth droids will be destroyed.
In the second test the first and second droids will be destroyed. | instruction | 0 | 76,256 | 14 | 152,512 |
Tags: binary search, data structures, two pointers
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq,bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default, 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,m,k=map(int,input().split())
a=[]
ans=[]
f=0
for i in range(n):
a.append(list(map(int,input().split())))
su=0
for j in range(m):
su+=a[i][j]
if su<=k:
f=1
ans=a[-1]+[]
if f==0:
ar=[0]*m
print(*ar)
def find(x):
fi=[[]for i in range(m)]
for i in range(m):
q=deque([])
for j in range(x-1):
while(len(q)>0 and q[-1][0]<=a[j][i]):
q.pop()
q.append((a[j][i],j))
for j in range(x-1,n):
while (len(q)>0 and q[-1][0]<=a[j][i]):
q.pop()
q.append((a[j][i],j))
while(q[0][1]<=j-x):
q.popleft()
fi[i].append(q[0][0])
for i in range(len(fi[0])):
q=[]
su=0
for j in range(m):
su+=fi[j][i]
q.append(fi[j][i])
if su<=k:
return q
return []
st=1
end=n
while(st<=end):
mid=(st+end)//2
f=find(mid)
if f==[]:
end=mid-1
else:
ans=f
st=mid+1
print(*ans)
``` | output | 1 | 76,256 | 14 | 152,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An army of n droids is lined up in one row. Each droid is described by m integers a1, a2, ..., am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it).
A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?
Input
The first line contains three integers n, m, k (1 ≤ n ≤ 105, 1 ≤ m ≤ 5, 0 ≤ k ≤ 109) — the number of droids, the number of detail types and the number of available shots, respectively.
Next n lines follow describing the droids. Each line contains m integers a1, a2, ..., am (0 ≤ ai ≤ 108), where ai is the number of details of the i-th type for the respective robot.
Output
Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.
If there are multiple optimal solutions, print any of them.
It is not necessary to make exactly k shots, the number of shots can be less.
Examples
Input
5 2 4
4 0
1 2
2 1
0 2
1 3
Output
2 2
Input
3 2 4
1 2
1 3
2 2
Output
1 3
Note
In the first test the second, third and fourth droids will be destroyed.
In the second test the first and second droids will be destroyed. | instruction | 0 | 76,257 | 14 | 152,514 |
Tags: binary search, data structures, two pointers
Correct Solution:
```
from itertools import tee
from sys import setrecursionlimit
from sys import stdin
setrecursionlimit(1000000007)
_data = iter(stdin.read().split('\n'))
def input():
return next(_data)
class SegTree:
def __init__(self, n, zero, f):
while n & (n - 1):
n -= n & -n
self.n = 2 * n
self.zero = zero
self.f = f
self.t = [self.zero for _ in range(2 * self.n - 1)]
def __getitem__(self, k):
return self.t[k + self.n - 1]
def __setitem__(self, k, v):
k += self.n - 1
self.t[k] = v
while k > 0:
k = (k - 1) >> 1
self.t[k] = self.f(self.t[2 * k + 1], self.t[2 * k + 2])
def query(self, a, b):
ans = self.zero
t1 = [0]
t2 = [0]
t3 = [self.n]
while t1:
k, l, r = t1.pop(), t2.pop(), t3.pop()
if b <= l or r <= a:
continue
elif a <= l and r <= b:
ans = self.f(self.t[k], ans)
else:
t1.append(2 * k + 1), t2.append(l), t3.append((l + r) >> 1)
t1.append(2 * k + 2), t2.append((l + r) >> 1), t3.append(r)
return ans
n, m, k = [int(x) for x in input().split()]
st = tuple(SegTree(n, 0, max) for _ in range(m))
rv = -1
rt = (0,) * m
p = 0
t = [0] * m
for i in range(n):
a = tuple(int(x) for x in input().split())
for j in range(m):
st[j][i] = a[j]
t[j] = max(t[j], a[j])
while sum(t) > k:
p += 1
for j in range(m):
t[j] = st[j].query(p, i + 1)
if rv < (i + 1) - p:
rv = (i + 1) - p
rt = tuple(t)
print(*rt)
``` | output | 1 | 76,257 | 14 | 152,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An army of n droids is lined up in one row. Each droid is described by m integers a1, a2, ..., am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it).
A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?
Input
The first line contains three integers n, m, k (1 ≤ n ≤ 105, 1 ≤ m ≤ 5, 0 ≤ k ≤ 109) — the number of droids, the number of detail types and the number of available shots, respectively.
Next n lines follow describing the droids. Each line contains m integers a1, a2, ..., am (0 ≤ ai ≤ 108), where ai is the number of details of the i-th type for the respective robot.
Output
Print m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.
If there are multiple optimal solutions, print any of them.
It is not necessary to make exactly k shots, the number of shots can be less.
Examples
Input
5 2 4
4 0
1 2
2 1
0 2
1 3
Output
2 2
Input
3 2 4
1 2
1 3
2 2
Output
1 3
Note
In the first test the second, third and fourth droids will be destroyed.
In the second test the first and second droids will be destroyed. | instruction | 0 | 76,258 | 14 | 152,516 |
Tags: binary search, data structures, two pointers
Correct Solution:
```
n,m,k = map(int, input().split())
mCnt = 0
ans = [0]*m
start = 0
end = 0
Q = [[] for i in range(m)]
for i in range(n):
A = list(map(int, input().split()))
z = 0
for j in range(m) :
while Q[j] and Q[j][-1][0] < A[j] :
Q[j].pop()
Q[j].append([A[j],i])
z += Q[j][0][0]
if z <= k :
end = i+1
if mCnt < end - start :
mCnt = end - start
for j in range(m) :
ans[j] = Q[j][0][0]
else :
while True :
z = 0
for j in range(m) :
if Q[j] and Q[j][0][1] == start :
Q[j].pop(0)
if Q[j] : z += Q[j][0][0]
start += 1
if z<= k : break
end += 1
for i in ans :
print(i, end = " ")
``` | output | 1 | 76,258 | 14 | 152,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start.
Input
The single line contains three integers T, S, q (2 ≤ q ≤ 104, 1 ≤ S < T ≤ 105).
Output
Print a single integer — the number of times the song will be restarted.
Examples
Input
5 2 2
Output
2
Input
5 4 7
Output
1
Input
6 2 3
Output
1
Note
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | instruction | 0 | 76,274 | 14 | 152,548 |
Tags: implementation, math
Correct Solution:
```
t, s, q = map(int, input().split())
cnt = 0
while s < t:
s = s * q
cnt += 1
print(cnt)
``` | output | 1 | 76,274 | 14 | 152,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start.
Input
The single line contains three integers T, S, q (2 ≤ q ≤ 104, 1 ≤ S < T ≤ 105).
Output
Print a single integer — the number of times the song will be restarted.
Examples
Input
5 2 2
Output
2
Input
5 4 7
Output
1
Input
6 2 3
Output
1
Note
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | instruction | 0 | 76,275 | 14 | 152,550 |
Tags: implementation, math
Correct Solution:
```
__author__ = 'Алексей'
T, S, q = map(int, input().split())
cnt, total = 1, q*S
while total < T:
cnt += 1
total *= q
print(cnt)
``` | output | 1 | 76,275 | 14 | 152,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start.
Input
The single line contains three integers T, S, q (2 ≤ q ≤ 104, 1 ≤ S < T ≤ 105).
Output
Print a single integer — the number of times the song will be restarted.
Examples
Input
5 2 2
Output
2
Input
5 4 7
Output
1
Input
6 2 3
Output
1
Note
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | instruction | 0 | 76,277 | 14 | 152,554 |
Tags: implementation, math
Correct Solution:
```
t,s,q=[int(j) for j in input().split()]
k=s
ans=0
q=q-1
while k<t:
k=k+(k*q)
ans=ans+1
print(ans)
``` | output | 1 | 76,277 | 14 | 152,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start.
Input
The single line contains three integers T, S, q (2 ≤ q ≤ 104, 1 ≤ S < T ≤ 105).
Output
Print a single integer — the number of times the song will be restarted.
Examples
Input
5 2 2
Output
2
Input
5 4 7
Output
1
Input
6 2 3
Output
1
Note
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | instruction | 0 | 76,278 | 14 | 152,556 |
Tags: implementation, math
Correct Solution:
```
n,m,r=map(int,input().split());o=0
while(m<n):
m*=r;o+=1
print(o)
``` | output | 1 | 76,278 | 14 | 152,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start.
Input
The single line contains three integers T, S, q (2 ≤ q ≤ 104, 1 ≤ S < T ≤ 105).
Output
Print a single integer — the number of times the song will be restarted.
Examples
Input
5 2 2
Output
2
Input
5 4 7
Output
1
Input
6 2 3
Output
1
Note
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case. | instruction | 0 | 76,281 | 14 | 152,562 |
Tags: implementation, math
Correct Solution:
```
def mp(): return map(int,input().split())
def lt(): return list(map(int,input().split()))
def pt(x): print(x)
def ip(): return input()
def it(): return int(input())
def sl(x): return [t for t in x]
def spl(x): return x.split()
def aj(liste, item): liste.append(item)
def bin(x): return "{0:b}".format(x)
def listring(l): return ' '.join([str(x) for x in l])
def printlist(l): print(' '.join([str(x) for x in l]))
t,s,q = mp()
time = 0
while s < t:
s *= q
time += 1
print(time)
``` | output | 1 | 76,281 | 14 | 152,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.
Tell Lesha, for how many times he will start the song, including the very first start.
Input
The single line contains three integers T, S, q (2 ≤ q ≤ 104, 1 ≤ S < T ≤ 105).
Output
Print a single integer — the number of times the song will be restarted.
Examples
Input
5 2 2
Output
2
Input
5 4 7
Output
1
Input
6 2 3
Output
1
Note
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.
In the second test, the song is almost downloaded, and Lesha will start it only once.
In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case.
Submitted Solution:
```
t, s, q = map(int, input().split())
answer, loaded = 1, s
for i in range(1, t+1):
loaded += (q-1)/q
loaded = round(loaded, 6)
loaded -= 1
#print('loaded', loaded)
if loaded < 0:
answer += 1
loaded = i - 1
print(answer)
``` | instruction | 0 | 76,286 | 14 | 152,572 |
No | output | 1 | 76,286 | 14 | 152,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | instruction | 0 | 76,302 | 14 | 152,604 |
Tags: data structures, sortings
Correct Solution:
```
'''class data:
def __init__(self,a):
self.data=a
def qsort(self,l,r,reverse):
if l>=r :
return None
ind=l
i=l
j=r
key=self.data[l]
while i<j :
if reverse==1:
while (self.data[j]>=key) & (j>=l):
j-=1
while (self.data[i]<key) & (i<=r) :
i+=1
ind=i-1
if i<j :
ind+=1
t=self.data[i]
self.data[i]=self.data[j]
self.data[j]=t
else :
while (self.data[j]<=key) & (j>=l) :
j-=1
ind=j+1
while (self.data[i]>key) & (i<=r) :
i+=1
if i<j :
ind-=1
t=self.data[i]
self.data[i]=self.data[j]
self.data[j]=t
self.qsort(l,ind,reverse)
self.qsort(ind+1,r,reverse)'''
n,m=[int(i) for i in input().split()]
adata=[int(i) for i in input().split()]
t=[None]*m
r=[None]*m
for i in range(m):
t[i],r[i]=[int(j) for j in input().split()]
Sortlist=[]
Sortcount=0
M=0
for i in range(m-1,-1,-1) :
if r[i]>M :
Sortlist.append([r[i],t[i]])
Sortcount+=1
M=r[i]
#a.qsort(0,Sortlist[-1][0]-1,1)
S=sorted(adata[0:Sortlist[-1][0]])
L=0
R=M-1
for i in range(M-1,-1,-1) :
if (Sortcount>0):
if (i<Sortlist[Sortcount-1][0]) :
Reverse=Sortlist[Sortcount-1][1]
Sortcount-=1
if Reverse==1 :
adata[i]=S[R]
R-=1
else :
adata[i]=S[L]
L+=1
for i in adata[0:-1] :
print(str(i)+" ",end="")
print(adata[-1])
``` | output | 1 | 76,302 | 14 | 152,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | instruction | 0 | 76,303 | 14 | 152,606 |
Tags: data structures, sortings
Correct Solution:
```
n,m = [int(i) for i in input().split()]
a = list(map(int,input().split()))
b = []
for i in range(m):
t,r = [int(x) for x in input().split()]
while len(b) > 0 and r >= b[-1][1]:
b.pop()
b.append([t,r])
t,r = 0, b[0][1]
b.append([0,0])
f = sorted(a[:r])
for i in range(1,len(b)):
for y in range(b[i-1][1],b[i][1],-1):
if b[i-1][0] == 1:
a[y-1] = f[r-1]
r -= 1
else:
a[y-1] = f[t]
t += 1
print (' '.join(list(str(i) for i in a)))
``` | output | 1 | 76,303 | 14 | 152,607 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | instruction | 0 | 76,304 | 14 | 152,608 |
Tags: data structures, sortings
Correct Solution:
```
def main():
from collections import deque
n, m = map(int, input().split())
aa = list(map(int, input().split()))
l = list(tuple(map(int, input().split())) for _ in range(m))
tmp, r0, t0 = [(0, 0)], 0, 0
for t, r in reversed(l):
if r0 < r:
r0 = r
if t0 != t:
t0 = t
tmp.append((t, r))
else:
tmp[-1] = (t, r)
t0, r0 = tmp.pop()
q = deque(sorted(aa[:r0]))
aa = aa[r0:]
aa.reverse()
ff = (None, q.pop, q.popleft)
for t, r in reversed(tmp):
f = ff[t0]
for i in range(r0 - r):
aa.append(f())
t0, r0 = t, r
print(' '.join(map(str, reversed(aa))))
if __name__ == '__main__':
main()
``` | output | 1 | 76,304 | 14 | 152,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | instruction | 0 | 76,305 | 14 | 152,610 |
Tags: data structures, sortings
Correct Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = []
t = []
for i in range(m):
x, y = map(int, input().split())
while len(t) > 0 and y >= t[-1][1]:
t.pop()
t.append([x, y])
x, y = 0, t[0][1] - 1
t.append([0, 0])
b = sorted(a[:y + 1])
for i in range(1, len(t)):
for j in range(t[i - 1][1], t[i][1], -1):
if (t[i - 1][0] == 1):
a[j - 1] = b[y]
y -= 1
else:
a[j - 1] = b[x]
x += 1
print(" ".join(list(str(i) for i in a)))
``` | output | 1 | 76,305 | 14 | 152,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | instruction | 0 | 76,306 | 14 | 152,612 |
Tags: data structures, sortings
Correct Solution:
```
from collections import *
from sys import stdin
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return list(stdin.readline()[:-1])
n, m = arr_inp(1)
a, mem, ans, en = arr_inp(1), defaultdict(lambda: [0, 0]), deque(), n - 1
for i in range(m):
t, r = arr_inp(1)
mem[r] = [t, i]
for i in range(n - 1, -1, -1):
if not mem[i + 1][0]:
ans.appendleft(a[i])
en -= 1
else:
break
tem, last, time = deque(sorted(a[:en + 1])), 0, -1
for j in range(en, -1, -1):
if mem[j + 1][0] == 1 and mem[j + 1][1] > time:
ans.appendleft(tem.pop())
last, time = 1, mem[j + 1][1]
elif mem[j + 1][0] == 2 and mem[j + 1][1] > time:
ans.appendleft(tem.popleft())
last, time = 2, mem[j + 1][1]
elif last == 1:
ans.appendleft(tem.pop())
else:
ans.appendleft(tem.popleft())
print(*ans)
``` | output | 1 | 76,306 | 14 | 152,613 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | instruction | 0 | 76,307 | 14 | 152,614 |
Tags: data structures, sortings
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq 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=998244353
EPS=1e-6
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()
n,m=value()
a=array()
status=defaultdict(int)
till=-1
given=[]
for i in range(m):
s,r=value()
given.append((s,r))
for s,r in given[::-1]:
if(r-1>till):
till=r-1
if(s==2):s=-1
status[r-1]=s*(-1)
# print(status)
ans=[-1]*n
have=a[:till+1]
for i in range(till+1,n):
ans[i]=a[i]
have.sort()
inc=1
low=0
high=till
# print(till,have)
for i in range(till,-1,-1):
if(status[i]!=0):
inc=status[i]
if(status[i]==1):
ind=low
else:
ind=high
if(inc==1):
ans[i]=have[low]
low+=1
else:
ans[i]=have[high]
high-=1
print(*ans)
``` | output | 1 | 76,307 | 14 | 152,615 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | instruction | 0 | 76,308 | 14 | 152,616 |
Tags: data structures, sortings
Correct Solution:
```
def compress(ops):
cops = []
for r, dir in ops:
while cops and cops[-1][0] <= r:
cops.pop()
if not cops or cops[-1][1] != dir:
cops.append((r, dir))
return cops
def transform(lst, ops):
mr, mdir = ops[0]
sections = [range(mr, len(lst))]
ost = 0
oen = mr
pr, pdir = ops[0]
for r, dir in ops[1:]:
k = pr-r
if pdir:
sections.append(reversed(range(ost, ost+k)))
ost += k
else:
sections.append(range(oen-k, oen))
oen -= k
pr, pdir = r, dir
if pdir:
sections.append(reversed(range(ost, oen)))
else:
sections.append(range(ost, oen))
olst = lst[:mr]
olst.sort()
olst.extend(lst[mr:])
return [olst[i] for sec in reversed(sections) for i in sec]
def parse_op():
d, r = input().split()
return int(r), (d == '2')
def parse_input():
n, m = map(int, input().split())
lst = list(map(int, input().split()))
assert len(lst) == n
ops = [parse_op() for _ in range(m)]
return lst, ops
if __name__ == '__main__':
lst, ops = parse_input()
cops = compress(ops)
tlst = transform(lst, cops)
print(' '.join(map(str, tlst)))
``` | output | 1 | 76,308 | 14 | 152,617 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. | instruction | 0 | 76,309 | 14 | 152,618 |
Tags: data structures, sortings
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
n,m = map(int,input().split())
a = list(map(int,input().split()))
s = []
for i in range(m):
t,r = map(int,input().split())
t -= 1
r -= 1
while s and s[-1][1] <= r: # operation will get overwritten so remove it
s.pop()
s.append([t,r])
s.append([-1,-1]) # dummy operation
sorted_slice = sorted(a[:s[0][1]+1])
# pointers for active part of slice
l = 0
r = s[0][1]
for i in range(len(s)-1):
if s[i][0]:
for j in range(s[i][1], s[i+1][1], -1):
a[j] = sorted_slice[l]
l += 1
else:
for j in range(s[i][1], s[i+1][1], -1):
a[j] = sorted_slice[r]
r -= 1
print(*a)
``` | output | 1 | 76,309 | 14 | 152,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
Submitted Solution:
```
a, b = (int(i) for i in input().split())
f = list(map(int,input().split()))
d = []
for i in range(b):
c, e = (int(t) for t in input().split())
while len(d) > 0 and e > d[-1][1]:
d.pop()
d.append([c, e])
c, e = 0, d[0][1]
d.append([0, 0])
g = sorted(f[:e])
for i in range(1,len(d)):
for y in range(d[i - 1][1], d[i][1], -1):
if d[i - 1][0] == 1:
f[y - 1] = g[e - 1]
e -= 1
else:
f[y - 1] = g[c]
c += 1
print(' '.join(list(str(i) for i in f)))
``` | instruction | 0 | 76,310 | 14 | 152,620 |
Yes | output | 1 | 76,310 | 14 | 152,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
Submitted Solution:
```
#!/usr/bin/python3
class StdReader:
def read_int(self):
return int(self.read_string())
def read_ints(self, sep = None):
return [int(i) for i in self.read_strings(sep)]
def read_float(self):
return float(self.read_string())
def read_floats(self, sep = None):
return [float(i) for i in self.read_strings(sep)]
def read_string(self):
return input()
def read_strings(self, sep = None):
return self.read_string().split(sep)
reader = StdReader()
def part_sort(a, i, j, reverse=False):
a[i:j] = sorted(a[i:j], reverse=reverse)
def part_sorted(b, i, j, reverse=False):
a = list(b)
part_sort(a, i, j, reverse)
return a
def main():
n, m = reader.read_ints()
a = reader.read_ints()
ops = []
for i in range(m):
t, r = reader.read_ints()
op = (t, r)
while ops and op[1] >= ops[-1][1]:
ops.pop()
ops.append(op)
# newops = []
# prevt = None
# for op in ops:
# if prevt is None or prevt != op[0]:
# newops.append(op)
# # max_r = max(max_r, op[1])
# prevt = op[0]
# ops = newops
max_r = ops[0][1]
b = sorted(a[:max_r])
bl = 0
br = max_r - 1
for i in range(len(ops)):
t, r = ops[i]
r1 = 0
if i < len(ops) - 1:
t1, r1 = ops[i+1]
k = r - r1
if t == 1:
for p in range(k):
a[r - 1 - p] = b[br]
br -= 1
else:
for p in range(k):
a[r - 1 - p] = b[bl]
bl += 1
# for op in ops:
# t, r = op
# reverse = t != 1
# part_sort(a, 0, r, reverse=reverse)
for ai in a:
print(ai, end=' ')
if __name__ == '__main__':
main()
``` | instruction | 0 | 76,311 | 14 | 152,622 |
Yes | output | 1 | 76,311 | 14 | 152,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
Submitted Solution:
```
n,m=map(int,input().split())
lis=list(map(int,input().split()))
q=[]
for i in range(m):
a,b=map(int,input().split())
while len(q)>0 and b>=q[-1][1]:
q.pop()
q.append([a,b])
a,b=0,q[0][1]-1
q.append([0,0])
aa=sorted(lis[:b+1])
for i in range(1,len(q)):
for j in range(q[i-1][1],q[i][1],-1):
if q[i-1][0]==1:
lis[j-1]=aa[b]
b-=1
else:
lis[j-1]=aa[a]
a+=1
print(*lis)
``` | instruction | 0 | 76,312 | 14 | 152,624 |
Yes | output | 1 | 76,312 | 14 | 152,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
Submitted Solution:
```
[n,m]=[int(i) for i in input().split()];
a=[int(i) for i in input().split()];
t=m*[0];
r=m*[0];
for k in range(0,m):
[t[k],r[k]]=[int(i) for i in input().split()];
tt=[];
rr=[];
mm=-1;
lastt=-1;
tt.append(t[0]);
rr.append(r[0]);
top=0;
for i in range(1,m):
while(top>-1):
if(r[i]>=rr[top]):
rr.pop();
tt.pop();
top=top-1;
else:
break;
if(top==-1):
rr.append(r[i]);
tt.append(t[i]);
top=top+1;
else:
if(tt[top]!=t[i]):
rr.append(r[i]);
tt.append(t[i]);
top=top+1;
r0=rr[0];
sorteda=sorted(a[:r0]);
b=0;
end=len(sorteda)-1;
for mindex in range(0,len(tt)-1):
rthis=rr[mindex];
rnext=rr[mindex+1];
if(tt[mindex]==1):
for i in range(rthis-1,rnext-1,-1):
a[i]=sorteda[end];
end=end-1;
else:
for i in range(rthis-1,rnext-1,-1):
a[i]=sorteda[b];
b=b+1;
if(tt[-1]==1):
for i in range(0,rr[-1]):
a[i]=sorteda[i+b];
else:
for i in range(0,rr[-1]):
a[i]=sorteda[end-i];
print(*a, sep=" ")
``` | instruction | 0 | 76,313 | 14 | 152,626 |
Yes | output | 1 | 76,313 | 14 | 152,627 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
Submitted Solution:
```
[n,m]=[int(i) for i in input().split()];
a=[int(i) for i in input().split()];
t=m*[0];
r=m*[0];
for k in range(0,m):
[t[k],r[k]]=[int(i) for i in input().split()];
tt=[];
rr=[];
lastt=-1;
mm=-1;
maxr=-2;
while(True):
maxr=-1;
for i in range(mm+1,m):
if((r[i]>=maxr) and (t[i]!=lastt)):
maxr=r[i];
mm=i;
if(maxr==-1):
break;
lastt=t[mm];
tt.append(t[mm]);
rr.append(r[mm]);
r0=rr[0];
sorteda=sorted(a[:r0]);
b=0;
end=len(sorteda)-1;
for mindex in range(0,len(tt)-1):
rthis=rr[mindex];
rnext=rr[mindex+1];
if(tt[mindex]==1):
for i in range(rthis-1,rnext-1,-1):
a[i]=sorteda[end];
end=end-1;
else:
for i in range(rthis-1,rnext-1,-1):
a[i]=sorteda[b];
b=b+1;
if(tt[-1]==1):
for i in range(0,rr[-1]):
a[i]=sorteda[i+b];
else:
for i in range(0,rr[-1]):
a[i]=sorteda[end-i];
print(*a, sep=" ")
``` | instruction | 0 | 76,314 | 14 | 152,628 |
No | output | 1 | 76,314 | 14 | 152,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
Submitted Solution:
```
a,b=input().split()
a=int(a)
b=int(b)
c=input().split()
for i in range(b):
d,e=input().split()
d=int(d)
e=int(e)
c1=c[0:e]
c1.sort(reverse=d-1)
c1.extend(c[e:])
c=c1
for i in range(a):
print(c[i],end=' ')
``` | instruction | 0 | 76,315 | 14 | 152,630 |
No | output | 1 | 76,315 | 14 | 152,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
Submitted Solution:
```
n, m = map(int, input().split())
xs = list(map(int, input().split()))
ys = []
for _ in range(m):
t, r = map(int, input().split())
while len(ys) > 0 and ys[-1][1] <= r:
ys.pop()
if len(ys) > 0 and ys[-1][0] == t:
pass
ys.append((t, r))
rmax = ys[0][1]
tmax = ys[0][0]
zs = xs[:rmax]
zs.sort()
xs[:rmax] = zs
print(ys)
for y in ys:
t, r = y
xs[:r] = reversed(xs[:r])
for x in xs:
print(x, end=' ')
``` | instruction | 0 | 76,316 | 14 | 152,632 |
No | output | 1 | 76,316 | 14 | 152,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).
Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively.
The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager.
Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (<image>, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.
Output
Print n integers — the final report, which will be passed to Blake by manager number m.
Examples
Input
3 1
1 2 3
2 2
Output
2 1 3
Input
4 2
1 2 4 3
2 3
1 2
Output
2 4 1 3
Note
In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.
In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.
Submitted Solution:
```
def sort(x,t,r):
temp=x[:r]
temp.sort(reverse=t-1)
return temp+x[r:]
from collections import deque as d
n,m=[int(i) for i in input().split()]
data=input().split()
operators=d()
ranges=[]
for i in range(m):
t,r=[int(i) for i in input().split()]
operators.append([t,r])
ranges.append([r,i])
ranges.sort(key=lambda x:(-x[0],-x[1]))
tindex=0
filtered=d([])
for i in ranges:
if tindex<=i[1]:
tindex=i[1]
filtered.append(operators[tindex])
for i in filtered:
data=sort(data,i[0],i[1])
print(' '.join(data))
'''class data():
def __init__(self,data):
self.data=data
def getData(self):
a=map(str,self.data)
return ' '.join(a)
def sort(self,r,t,l):
temp=self.data[:r]
temp.sort(reverse=t-1)
self.data=temp+self.data[r:]
n,m=[int(i) for i in input().split()]
data=data([int(i) for i in input().split()])
operators=d()
ranges=d()
useful=d()
for i in range(m):
t,r=[int(i) for i in input().split()]
operators.append([t,r])
ranges.append(r)
while ranges:
a=operators.popleft()
ranges.popleft()
if ranges and a[1]>max(ranges):
useful.append(a)
elif not ranges:
useful.append(a)
useful.append([0,0])
for i in range(len(useful)-1):
data.sort(useful[i][1],useful[i][0],useful[i+1][1])
print(data.getData())'''
``` | instruction | 0 | 76,317 | 14 | 152,634 |
No | output | 1 | 76,317 | 14 | 152,635 |
Provide tags and a correct Python 3 solution for this coding contest problem.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4. | instruction | 0 | 76,383 | 14 | 152,766 |
Tags: implementation
Correct Solution:
```
R=lambda:map(int,input().split())
n,m=R()
l=list(R())
a=[None]*n
c =set(range(1, n + 1))
for i in range(m-1):
j=l[i]-1
d=l[i+1]-l[i]
if d<=0:
d+=n
if a[j]!=d:
if a[j] or d not in c:
print(-1)
exit()
a[j]=d
c.remove(d)
for i in range(n):
if a[i] is None:
a[i]=c.pop()
print(*a)
``` | output | 1 | 76,383 | 14 | 152,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4. | instruction | 0 | 76,384 | 14 | 152,768 |
Tags: implementation
Correct Solution:
```
n,m=map(int,input().split())
ans=[None]*n
l=list(map(int,input().split()))
for i in range(1,m):
d=(l[i]-l[i-1])%n
if d==0:
d+=n
if ans[l[i-1]-1]==None or ans[l[i-1]-1]==d:
ans[l[i-1]-1]=d
else:
print(-1)
quit()
l=[i+1 for i in range(n)]
for i in ans:
if i in l:
l.remove(i)
elif i!=None:
print(-1)
quit()
for i in ans:
if i==None:
print(l[-1],end=" ")
l.pop()
else:
print(i,end=" ")
``` | output | 1 | 76,384 | 14 | 152,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4. | instruction | 0 | 76,385 | 14 | 152,770 |
Tags: implementation
Correct Solution:
```
n, m = [int(i) for i in input().split()]
l = [int(i) - 1 for i in input().split()]
ans = [-1] * n
for i in range(m - 1):
t = (l[i + 1] - l[i]) % n
if t == 0:
t = n
if ans[l[i]] != -1 and ans[l[i]] != t:
print(-1)
break
ans[l[i]] = t
else:
s = set()
for i in ans:
if i != -1:
s.add(i)
c = 1
for i in range(n):
if ans[i] == -1:
while c in s:
c += 1
ans[i] = c
s.add(c)
if len(set(ans)) == n:
print(' '.join([str(i) for i in ans]))
else:
print(-1)
``` | output | 1 | 76,385 | 14 | 152,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4. | instruction | 0 | 76,386 | 14 | 152,772 |
Tags: implementation
Correct Solution:
```
n,m = map(int, input().split())
l = list(map(int, input().split()))
a = [-1]*(n + 1)
s = [True] + [False]*n
for i in range(m - 1):
curr = l[i + 1] - l[i]
if curr <= 0:
curr += n
if a[l[i]] == curr:
continue
if s[curr] or a[l[i]] != -1:
print("-1")
exit()
s[curr] = True
a[l[i]] = curr
for i,x in enumerate(a[1:]):
if x == -1:
for j in range(len(s)):
if s[j] == False:
s[j] = True
a[i + 1] = j
break
print(" ".join(str(x) for x in a[1:]))
``` | output | 1 | 76,386 | 14 | 152,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4. | instruction | 0 | 76,387 | 14 | 152,774 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
ans = [0] * (n + 1)
for i in range(m - 1):
pot = (a[i + 1] - a[i] + n) % n
if pot == 0: pot = n
if ans[a[i]] == 0 or ans[a[i]] == pot: ans[a[i]] = pot
else:
print(-1)
exit(0)
used = [False] * (n + 1)
for i in ans:
used[i] = True
for i in range(1, n + 1):
if ans[i] == 0:
for j in range(1, n + 1):
if not used[j]:
used[j] = True
ans[i] = j
break
print(' '.join(map(str, ans[1:])) if all(used[1:]) else -1)
``` | output | 1 | 76,387 | 14 | 152,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4. | instruction | 0 | 76,388 | 14 | 152,776 |
Tags: implementation
Correct Solution:
```
from sys import stdin, stdout
n, m = map(int, stdin.readline().split())
position = list(map(int, stdin.readline().split()))
ans = [0 for i in range(n + 1)]
used = set()
label = 1
for i in range(m - 1):
if not ans[position[i]]:
if not (position[i + 1] - position[i]):
ans[position[i]] = n
if n not in used:
used.add(n)
else:
label = 0
else:
ans[position[i]] = (position[i + 1] - position[i]) % n
if (position[i + 1] - position[i]) % n not in used:
used.add((position[i + 1] - position[i]) % n)
else:
label = 0
elif (position[i + 1] - position[i]) and ans[position[i]] != (position[i + 1] - position[i]) % n:
label = 0
elif not (position[i + 1] - position[i]) and ans[position[i]] != n:
label = 0
position = []
for i in range(1, n + 1):
if not ans[i]:
position.append(i)
if label:
for i in range(1, n + 1):
if i not in used:
ans[position.pop()] = i
if not label:
stdout.write('-1')
else:
stdout.write(' '.join(list(map(str, ans[1:]))))
``` | output | 1 | 76,388 | 14 | 152,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4. | instruction | 0 | 76,389 | 14 | 152,778 |
Tags: implementation
Correct Solution:
```
n,m=map(int, input().split())
p=[0]*(n+1)
seen=p.copy()
l=list(map(int,input().split()))
cnt=0
for i in range(m-1):
d=(l[i+1]-l[i]+n)%n
d= d if d!=0 else n
if seen[d]==1 and p[l[i]]!=d:
print(-1)
quit()
cnt+=1 if seen[d]==0 else 0
p[l[i]]=d
seen[d]=1
i,j=1,1
while i<=n:
if p[i]!=0:
i+=1
continue
while j<n and seen[j]==1 :
j+=1
p[i]=j
seen[j]=1
cnt+=1
i+=1
ans = [str(p[i]) for i in range(1,n+1)]
print(' '.join(ans)if cnt==n else -1)
``` | output | 1 | 76,389 | 14 | 152,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4. | instruction | 0 | 76,390 | 14 | 152,780 |
Tags: implementation
Correct Solution:
```
from collections import defaultdict
N, M = map(int, input().split())
L = list(map(int, input().split()))
A = [-1 for _ in range(N)]
U = defaultdict(bool)
def solve():
for i in range(M - 1):
cur = L[i] - 1
nxt = L[i + 1] - 1
delta = (nxt - cur) % N if nxt != cur else N
if A[cur] == -1 or A[cur] == delta:
A[cur] = delta
U[delta] = True
else:
return False
RA = [i for i, a in enumerate(A) if a == -1] # unfill positions
RU = [i for i in range(1, N + 1) if not U[i]] # unused numbers
if len(RA) != len(RU):
return False
for i, j in zip(RA, RU):
A[i] = j
U[j] = True
return True
if not solve():
print('-1')
else:
print(' '.join(map(str, A)))
``` | output | 1 | 76,390 | 14 | 152,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Submitted Solution:
```
f = lambda: map(int, input().split())
n, m = f()
p = list(f())
s = set(range(1, n + 1))
t = [0] * n
for x, y in zip(p, p[1:]):
q = (y - x) % n
if not q: q = n
if t[x - 1] == q: continue
if t[x - 1] or q not in s:
print(-1)
exit()
t[x - 1] = q
s.remove(q)
for q in t: print(q if q else s.pop())
``` | instruction | 0 | 76,391 | 14 | 152,782 |
Yes | output | 1 | 76,391 | 14 | 152,783 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Submitted Solution:
```
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,m=map(int,input().split())
l=list(map(int,input().split()))
for i in range(len(l)):
l[i]-=1
use=[0]*n
a=[0]*n
bad=0
for i in range(len(l)-1):
# transfer l[i] to l[i+1]
if a[l[i]] and a[l[i]]%n!=(l[i+1]-l[i])%n:
bad=1
break
use[(l[i+1]-l[i])%n]=1
a[l[i]]=(l[i+1]-l[i])%n
if a[l[i]]==0: a[l[i]]=n
if not bad:
# fill in gaps
for i in range(n):
if a[i]==0:
for j in range(1,n+1):
if not use[j%n]:
a[i]=j
use[j%n]=1
break
if sum(use)==n:
print(" ".join(map(str,a)))
else:
print("-1")
else:
print("-1")
``` | instruction | 0 | 76,392 | 14 | 152,784 |
Yes | output | 1 | 76,392 | 14 | 152,785 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Submitted Solution:
```
n, m = [int(x) for x in input().split()]
l = [int(x) for x in input().split()]
a = [-1]*(n+1)
t = True
d1 = set()
d = {}
for x in range(len(l)-1):
if(l[x+1]-l[x] == 0):
if(a[l[x]]!=-1 and a[l[x]]!=n):
t = False
d1.add(n)
if(n in d):
if( d[n]!=l[x] ):
t = False
else:
d[n]=l[x]
a[l[x]] = n
else:
if(l[x+1]-l[x] < 0):
if(a[l[x]]!=-1 and a[l[x]]!=n + l[x+1]-l[x]):
t = False
if(n + l[x+1]-l[x] in d):
if( d[n + l[x+1]-l[x]]!=l[x] ):
t = False
else:
d[n + l[x+1]-l[x]]=l[x]
d1.add(n + l[x+1]-l[x])
a[l[x]] = n + l[x+1]-l[x]
else:
if(a[l[x]]!=-1 and a[l[x]]!=l[x+1]-l[x]):
t = False
if(l[x+1]-l[x] in d):
if(d[l[x+1]-l[x]] != l[x]):
t = False
else:
d[l[x+1]-l[x]]=l[x]
d1.add(l[x+1]-l[x])
a[l[x]] = l[x+1]-l[x]
if(t == False):
print(-1)
else:
p = set([x for x in range(1,n+1)])
p -=d1
# t = 0
for x in range(1,n+1):
if(a[x]==-1):
print(p.pop(),end=' ')
# t+=1
continue
print(a[x],end=' ')
# print(a[x],end=' ')
``` | instruction | 0 | 76,393 | 14 | 152,786 |
Yes | output | 1 | 76,393 | 14 | 152,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Submitted Solution:
```
n, m = map(int, input().split())
l = list(map(int, input().split()))
a = [-1] * n
s = set(range(1, n + 1))
d = set()
for i in range(m - 1):
for j in range(1, n + 1):
if (l[i] + j - l[i + 1]) % n == 0:
if j in d and a[l[i] - 1] != j:
print(-1)
exit()
a[l[i] - 1] = j
d.add(j)
break
b = list(s - s.intersection(d))
k = 0
for i in range(n):
if a[i] == -1:
if k == len(b):
print(-1)
exit()
a[i] = b[k]
k += 1
print(*a)
``` | instruction | 0 | 76,394 | 14 | 152,788 |
Yes | output | 1 | 76,394 | 14 | 152,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Submitted Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
used = [False for _ in range(n + 1)]
ans = [0 for _ in range(n)]
f = True
for i in range(min(n, m - 1)):
d = (a[i + 1] - a[i] + n) % n
if ans[a[i] - 1] == 0 and not used[d]:
ans[a[i] - 1] = d
used[d] = True
elif ans[a[i] - 1] != d:
f = False
break
j = 1
for i in range(n):
while j < n and used[j]:
j += 1
if ans[i] == 0:
ans[i] = j
used[j] = True
idx = a[0] - 1
for i in range(m):
if idx + 1 != a[i]:
f = False
break
idx += ans[idx]
idx %= n
if f:
print(' '.join(list(map(str, ans))))
else:
print(-1)
``` | instruction | 0 | 76,395 | 14 | 152,790 |
No | output | 1 | 76,395 | 14 | 152,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Submitted Solution:
```
n, m =[int(i) for i in input().split()]
l = [int(i) - 1 for i in input().split()]
ans = [-1] * n
flag = 0
for i in range(m - 1):
t = (l[i + 1] - l[i]) % n
if t == 0:
t = n
if ans[l[i]] != -1 and ans[l[i]] != t:
break
ans[l[i]] = t
else:
s = set()
for i in ans:
if i != -1:
s.add(i)
c = 1
for i in range(n):
if ans[i] != -1:
while c in s:
c += 1
ans[i] = c
if len(set(ans)) == n:
print(' '.join([str(i) for i in ans]))
else:
print(-1)
``` | instruction | 0 | 76,396 | 14 | 152,792 |
No | output | 1 | 76,396 | 14 | 152,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Submitted Solution:
```
n, m = [int(x) for x in input().split()]
l = [int(x) for x in input().split()]
a = [-1]*(n+1)
for x in range(len(l)-1):
if(l[x+1]-l[x] == 0):
a[l[x]] = n
else:
a[l[x]] = abs(l[x+1]-l[x])
t = True
for x in range(1,n+1):
if(a[x]==-1):
t = False
if(t == False):
print("-1")
else:
for x in range(1,n+1):
print(a[x],end=' ')
``` | instruction | 0 | 76,397 | 14 | 152,794 |
No | output | 1 | 76,397 | 14 | 152,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers l1, l2, ..., lm — indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game.
Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input
The first line contains two integer numbers n, m (1 ≤ n, m ≤ 100).
The second line contains m integer numbers l1, l2, ..., lm (1 ≤ li ≤ n) — indices of leaders in the beginning of each step.
Output
Print such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Examples
Input
4 5
2 3 1 4 4
Output
3 1 2 4
Input
3 3
3 1 2
Output
-1
Note
Let's follow leadership in the first example:
* Child 2 starts.
* Leadership goes from 2 to 2 + a2 = 3.
* Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1.
* Leadership goes from 1 to 1 + a1 = 4.
* Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Submitted Solution:
```
n,m = map(int,input().strip(' ').split(' '))
A= list(map(int,input().strip(' ').split(' ')))
B=[0]*n
flag=False
# indices=[]
for i in range(len(A)-1):
t=A[i]
t2=A[i+1]
if(t2<=t):
if((t2-t+n) in B):
flag=True
break
k=(n+t2-t)
else:
if((t2-t)in B):
flag=True
break
k=(t2-t)
if(k>n):
k=k&n
B[t-1]=k
# indices.append(t-1)
if(0 in B):
flag=True
if(not flag):
for i in B:
print(i,end=' ')
print()
else:
print(-1)
# print()
``` | instruction | 0 | 76,398 | 14 | 152,796 |
No | output | 1 | 76,398 | 14 | 152,797 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.
Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.
Input
The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.
The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | instruction | 0 | 76,423 | 14 | 152,846 |
Tags: dp
Correct Solution:
```
import sys
def solv(v):
r = []
nr1 = 0
l = 0
for i in v:
mx = l
if i == 1:
nr1 += 1
else:
mx = l + 1
if nr1 > mx:
mx = nr1
r.append(mx)
l = mx
return r
f = sys.stdin
n = int(f.readline())
a = [int(number) for number in f.readline().split()]
b = [((x - 1) ^ 1) + 1 for x in a]
b.reverse()
ra = solv(a)
rb = solv(b)
mx = max(ra[n - 1], rb[n - 1])
for i in range(1, n):
mx = max(mx, ra[i - 1] + rb[n - i - 1])
print(mx)
``` | output | 1 | 76,423 | 14 | 152,847 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.
Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.
Input
The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.
The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | instruction | 0 | 76,424 | 14 | 152,848 |
Tags: dp
Correct Solution:
```
#t=int(input())
t=1
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
dp=[[0 for j in range(4)] for i in range(n)]
p1=[0]*(n+1)
p2=[0]*(n+1)
for i in range(n):
p1[i+1]+=p1[i]
p2[i+1]+=p2[i]
if l[i]==1:
p1[i+1]+=1
else:
p2[i+1]+=1
if l[0]==1:
dp[0][0]=1
else:
dp[0][1]=1
for i in range(1,n):
for j in range(i-1,-1,-1):
if l[i]==1:
dp[i][0]=p1[i+1]
dp[i][1]=max(dp[j][1],dp[i][1])
if dp[j][1]!=0:
dp[i][2]=max(dp[j][1]+1,dp[j][2]+1,dp[i][2])
else:
dp[i][2]=max(dp[j][2]+1,dp[i][2])
dp[i][3]=max(dp[j][2],dp[i][3])
else:
dp[i][0]=max(dp[j][0],dp[i][0])
if dp[j][0]!=0:
dp[i][1]=max(dp[j][1]+1,dp[j][0]+1,dp[i][1])
else:
dp[i][1]=max(dp[j][1]+1,dp[i][1])
dp[i][2]=dp[j][2]
if dp[j][2]!=0:
dp[i][3]=max(dp[j][3]+1,dp[j][2]+1,dp[i][3])
else:
dp[i][3]=max(dp[j][3]+1,dp[i][3])
maxi=0
for i in range(n):
for j in range(4):
maxi=max(maxi,dp[i][j])
print(maxi)
``` | output | 1 | 76,424 | 14 | 152,849 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.
Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.
Input
The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.
The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | instruction | 0 | 76,425 | 14 | 152,850 |
Tags: dp
Correct Solution:
```
n = int(input())
A = list(map(int, input().split()))
one = [0]
two = [0]
for i in A:
one.append(one[-1])
two.append(two[-1])
if i == 1:
one[-1] += 1
else:
two[-1] += 1
rdp1 = [[1] * n for _ in range(n)]
rdp2 = [[1] * n for _ in range(n)]
for l in range(n):
for r in range(l + 1, n):
if A[r] == 2:
rdp1[l][r] = rdp1[l][r - 1] + 1
else:
if rdp1[l][r - 1] == one[r] - one[l]:
rdp1[l][r] = rdp1[l][r - 1] + 1
else:
rdp1[l][r] = rdp1[l][r - 1]
if A[r] == 1:
rdp2[l][r] = rdp2[l][r - 1] + 1
else:
if rdp2[l][r - 1] == two[r] - two[l]:
rdp2[l][r] = rdp2[l][r - 1] + 1
else:
rdp2[l][r] = rdp2[l][r - 1]
dp = [0] * n
dp[0] = 1
for i in range(1, n):
if A[i] == 2:
dp[i] = dp[i - 1] + 1
else:
if dp[i - 1] == one[i]:
dp[i] = dp[i - 1] + 1
else:
dp[i] = dp[i - 1]
dp[i] = max(dp[i], rdp2[0][i])
for j in range(i):
if rdp1[0][j] == one[j + 1]:
dp[i] = max(dp[i], rdp1[0][j] + rdp2[j + 1][i])
dp[i] = max(dp[i], rdp1[0][j] + two[i + 1] - two[j + 1])
print(dp[-1])
``` | output | 1 | 76,425 | 14 | 152,851 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.
Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.
Input
The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.
The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | instruction | 0 | 76,426 | 14 | 152,852 |
Tags: dp
Correct Solution:
```
import sys
def input():
return sys.stdin.buffer.readline().rstrip()
n = int(input())
a = list(map(int, input().split()))
ans = max(a.count(1), a.count(2))
#mixed case
prefix = [0]*(n + 10)
suffix = [0]*(n + 10)
for i in range(n):
if a[i] == 1:
prefix[i + 1] = 1
a.reverse()
for i in range(n):
if a[i] == 2:
suffix[i + 1] = 1
a.reverse()
for i in range(n):
prefix[i + 1] += prefix[i]
suffix[i + 1] += suffix[i]
INF = 1 << 60
a.reverse()
ans = -INF
for l in range(n):
max_case_1 = 0
max_case_2 = 0
for r in range(l, n):
if a[r] == 1:
max_case_1 += 1
elif a[r] == 2:
max_case_2 = max(max_case_2, max_case_1) + 1
K = max(max_case_1, max_case_2)
ans = max(ans, K + prefix[n - 1 - r] + suffix[l])
print(ans)
``` | output | 1 | 76,426 | 14 | 152,853 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.
Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.
Input
The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.
The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | instruction | 0 | 76,427 | 14 | 152,854 |
Tags: dp
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
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-----------------------------------------------------
n = int(input())
a = list(map(int,input().split()))
count = [0]*4
for i in range(n):
if (a[i] == 1):
count[0] += 1
count[2] = max(count[1]+1,count[2]+1)
else:
count[1] = max(count[1]+1,count[0]+1)
count[3] = max(count[3]+1,count[2]+1)
print(max(count))
``` | output | 1 | 76,427 | 14 | 152,855 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.
Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.
Input
The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.
The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | instruction | 0 | 76,428 | 14 | 152,856 |
Tags: dp
Correct Solution:
```
#fek mikoni aslan lozoomi dare kasi tu in donya dustet dashtet bashe ?!
#age are chera tanhayi ?!!
#age na chera namordi ?!!!
DP = [0] * 4
input()
for x in map(int, input().split()):
if x == 1 :
DP[0] += 1
DP[2] += 1
else :
DP[1] += 1
DP[3] += 1
for j in range ( 1 , 4 ) :
DP[j] = max ( DP[j] , DP[j-1] )
print (DP[3])
``` | output | 1 | 76,428 | 14 | 152,857 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.
Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.
Input
The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.
The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | instruction | 0 | 76,429 | 14 | 152,858 |
Tags: dp
Correct Solution:
```
# import sys
# sys.stdin = open('in.txt', 'r')
n = int(input())
a = list(map(int, input().split()))
d = [0, 0, 0, 0]
for i in range(n):
if a[i] == 1:
d[0] += 1
d[2] = max(d[2], d[1])
d[2] += 1
else:
d[1] = max(d[1], d[0])
d[1] += 1
d[3] = max(d[3], d[2])
d[3] += 1
print(max(d))
``` | output | 1 | 76,429 | 14 | 152,859 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.