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.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly. | instruction | 0 | 59,978 | 14 | 119,956 |
Tags: dp, flows, graph matchings, greedy
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
p = []
for i in range(n):
if a[i] == 1:
p += [i]
dp = [[float('inf')]*(len(p)+1) for i in range(n+1)]
for i in range(n+1):
dp[i][0] = 0
for i in range(1, n+1):
for j in range(1, len(p)+1):
dp[i][j] = dp[i-1][j]
if a[i-1] == 0:
if not dp[i][j]:
dp[i][j] = min(dp[i][j-1], dp[i-1][j-1]) + abs((i-1) - p[j-1])
else:
dp[i][j] = min(dp[i][j], dp[i-1][j-1] + abs((i-1) -p[j-1]))
print(dp[n][len(p)])
``` | output | 1 | 59,978 | 14 | 119,957 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly. | instruction | 0 | 59,979 | 14 | 119,958 |
Tags: dp, flows, graph matchings, greedy
Correct Solution:
```
n,*a = map(int, open(0).read().split())
ones = [i for i in range(n) if a[i]]
needed_zeros = len(ones)
dp = [[1e9]*(needed_zeros+1) for i in range(n+1)]
for i in range(n+1):dp[i][0] = 0
for i in range(1, n+1):
for j in range(1, needed_zeros+1):
dp[i][j] = dp[i-1][j]
if a[i-1]==0:
dp[i][j] = min(dp[i][j], dp[i-1][j-1] + abs(ones[j-1]-(i-1)))
print(dp[n][needed_zeros])
``` | output | 1 | 59,979 | 14 | 119,959 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly. | instruction | 0 | 59,980 | 14 | 119,960 |
Tags: dp, flows, graph matchings, greedy
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=2**51, 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)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(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=int(input())
l=list(map(int,input().split()))
cur=set()
w=[]
for i in range(n):
if l[i]==1:
cur.add(i)
w.append(i)
dp = [[10**8 for i in range(n)] for j in range(len(w) + 1)]
for i in range(n):
dp[0][i] = 0
for i in range(1,len(w)+1):
dpmin=[0]*(n+1)
dpmin[0]=dp[i-1][0]
for j in range(1,n):
dpmin[j]=min(dpmin[j-1],dp[i-1][j])
if i==1 and 0 not in cur:
dp[i][0]=abs(w[0])
for j in range(1,n):
if j not in cur:
dp[i][j]=dpmin[j-1]+abs(w[i-1]-j)
print(min(dp[-1]))
``` | output | 1 | 59,980 | 14 | 119,961 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly. | instruction | 0 | 59,981 | 14 | 119,962 |
Tags: dp, flows, graph matchings, greedy
Correct Solution:
```
n=int(input())
aal=list(map(int, input().split()))
al=[]
bl=[]
k=0
emp=0
for i in range(n):
if aal[i]==0:
bl.append(i)
emp+=1
else:
al.append(i)
k+=1
if k==0:
print(0)
exit()
dp=[[10**10]*(emp+1) for _ in range(k+1)]
dp[0][0]=0
for i in range(1,k+1):
a=al[i-1]
mi=10**10
val_mi=10**10
for j in range(i,emp+1):
b=bl[j-1]
mi=min(mi, dp[i-1][j-1])
val_mi=min(mi+abs(a-b), val_mi)
dp[i][j]=val_mi
print(dp[k][emp])
# print(dp)
``` | output | 1 | 59,981 | 14 | 119,963 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly. | instruction | 0 | 59,982 | 14 | 119,964 |
Tags: dp, flows, graph matchings, greedy
Correct Solution:
```
INF = 10 ** 9
N = int(input())
A = list(map(int, input().split()))
B = []
for i in range(N):
if A[i]: B.append(i)
M = len(B)
DP = [[INF] * (N + 1) for _ in range(M + 1)]
DP[0][0] = 0
for i in range(M):
for j in range(N):
if A[j] == 0:
DP[i + 1][j + 1] = min(DP[i + 1][j + 1], DP[i][j] + abs(B[i] - j))
DP[i][j + 1] = min(DP[i][j + 1], DP[i][j])
print(min(DP[M]))
``` | output | 1 | 59,982 | 14 | 119,965 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Submitted Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import math
import os
import sys
from fractions import *
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import *
from collections import *
# sys.setrecursionlimit(10**5)
M = 10 ** 9 + 7
# print(math.factorial(5))
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
# sys.setrecursionlimit(10**6)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def inpu(): return int(inp())
# -----------------------------------------------------------------
def regularbracket(t):
p = 0
for i in t:
if i == "(":
p += 1
else:
p -= 1
if p < 0:
return False
else:
if p > 0:
return False
else:
return True
# -------------------------------------------------
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
# ------------------------------reverse string(pallindrome)
def reverse1(string):
pp = ""
for i in string[::-1]:
pp += i
if pp == string:
return True
return False
# --------------------------------reverse list(paindrome)
def reverse2(list1):
l = []
for i in list1[::-1]:
l.append(i)
if l == list1:
return True
return False
def mex(list1):
# list1 = sorted(list1)
p = max(list1) + 1
for i in range(len(list1)):
if list1[i] != i:
p = i
break
return p
def sumofdigits(n):
n = str(n)
s1 = 0
for i in n:
s1 += int(i)
return s1
def perfect_square(n):
s = math.sqrt(n)
if s == int(s):
return True
return False
# -----------------------------roman
def roman_number(x):
if x > 15999:
return
value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
symbol = ["F", "MF", "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
roman = ""
i = 0
while x > 0:
div = x // value[i]
x = x % value[i]
while div:
roman += symbol[i]
div -= 1
i += 1
return roman
def soretd(s):
for i in range(1, len(s)):
if s[i - 1] > s[i]:
return False
return True
# print(soretd("1"))
# ---------------------------
def countRhombi(h, w):
ct = 0
for i in range(2, h + 1, 2):
for j in range(2, w + 1, 2):
ct += (h - i + 1) * (w - j + 1)
return ct
def countrhombi2(h, w):
return ((h * h) // 4) * ((w * w) // 4)
# ---------------------------------
def binpow(a, b):
if b == 0:
return 1
else:
res = binpow(a, b // 2)
if b % 2 != 0:
return res * res * a
else:
return res * res
# -------------------------------------------------------
def binpowmodulus(a, b, m):
a %= m
res = 1
while (b > 0):
if (b & 1):
res = res * a % m
a = a * a % m
b >>= 1
return res
# -------------------------------------------------------------
def coprime_to_n(n):
result = n
i = 2
while (i * i <= n):
if (n % i == 0):
while (n % i == 0):
n //= i
result -= result // i
i += 1
if (n > 1):
result -= result // n
return result
# -------------------prime
def prime(x):
if x == 1:
return False
else:
for i in range(2, int(math.sqrt(x)) + 1):
# print(x)
if (x % i == 0):
return False
else:
return True
def luckynumwithequalnumberoffourandseven(x,n,a):
if x >= n and str(x).count("4") == str(x).count("7"):
a.append(x)
else:
if x < 1e12:
luckynumwithequalnumberoffourandseven(x * 10 + 4,n,a)
luckynumwithequalnumberoffourandseven(x * 10 + 7,n,a)
return a
#----------------------
def luckynum(x,l,r,a):
if x>=l and x<=r:
a.append(x)
if x>r:
a.append(x)
return a
if x < 1e10:
luckynum(x * 10 + 4, l,r,a)
luckynum(x * 10 + 7, l,r,a)
return a
def luckynuber(x, n, a):
p = set(str(x))
if len(p) <= 2:
a.append(x)
if x < n:
luckynuber(x + 1, n, a)
return a
# ------------------------------------------------------interactive problems
def interact(type, x):
if type == "r":
inp = input()
return inp.strip()
else:
print(x, flush=True)
# ------------------------------------------------------------------zero at end of factorial of a number
def findTrailingZeros(n):
# Initialize result
count = 0
# Keep dividing n by
# 5 & update Count
while (n >= 5):
n //= 5
count += n
return count
# -----------------------------------------------merge sort
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr) // 2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# -----------------------------------------------lucky number with two lucky any digits
res = set()
def solven(p, l, a, b, n): # given number
if p > n or l > 10:
return
if p > 0:
res.add(p)
solven(p * 10 + a, l + 1, a, b, n)
solven(p * 10 + b, l + 1, a, b, n)
# problem
"""
n = int(input())
for a in range(0, 10):
for b in range(0, a):
solve(0, 0)
print(len(res))
"""
# Python3 program to find all subsets
# by backtracking.
# In the array A at every step we have two
# choices for each element either we can
# ignore the element or we can include the
# element in our subset
def subsetsUtil(A, subset, index, d):
print(*subset)
s = sum(subset)
d.append(s)
for i in range(index, len(A)):
# include the A[i] in subset.
subset.append(A[i])
# move onto the next element.
subsetsUtil(A, subset, i + 1, d)
# exclude the A[i] from subset and
# triggers backtracking.
subset.pop(-1)
return d
def subsetSums(arr, l, r, d, sum=0):
if l > r:
d.append(sum)
return
subsetSums(arr, l + 1, r, d, sum + arr[l])
# Subset excluding arr[l]
subsetSums(arr, l + 1, r, d, sum)
return d
def print_factors(x):
factors = []
for i in range(1, x + 1):
if x % i == 0:
factors.append(i)
return (factors)
# -----------------------------------------------
def calc(X, d, ans, D):
# print(X,d)
if len(X) == 0:
return
i = X.index(max(X))
ans[D[max(X)]] = d
Y = X[:i]
Z = X[i + 1:]
calc(Y, d + 1, ans, D)
calc(Z, d + 1, ans, D)
# ---------------------------------------
def factorization(n, l):
c = n
if prime(n) == True:
l.append(n)
return l
for i in range(2, c):
if n == 1:
break
while n % i == 0:
l.append(i)
n = n // i
return l
# endregion------------------------------
def good(b):
l = []
i = 0
while (len(b) != 0):
if b[i] < b[len(b) - 1 - i]:
l.append(b[i])
b.remove(b[i])
else:
l.append(b[len(b) - 1 - i])
b.remove(b[len(b) - 1 - i])
if l == sorted(l):
# print(l)
return True
return False
# arr=[]
# print(good(arr))
def generate(st, s):
if len(s) == 0:
return
# If current string is not already present.
if s not in st:
st.add(s)
# Traverse current string, one by one
# remove every character and recur.
for i in range(len(s)):
t = list(s).copy()
t.remove(s[i])
t = ''.join(t)
generate(st, t)
return
#=--------------------------------------------longest increasing subsequence
def largestincreasingsubsequence(A):
l = [1]*len(A)
sub=[]
for i in range(1,len(l)):
for k in range(i):
if A[k]<A[i]:
sub.append(l[k])
l[i]=1+max(sub,default=0)
return max(l,default=0)
#----------------------------------longest palindromic substring
# Python3 program for the
# above approach
# Function to calculate
# Bitwise OR of sums of
# all subsequences
def findOR(nums, N):
# Stores the prefix
# sum of nums[]
prefix_sum = 0
# Stores the bitwise OR of
# sum of each subsequence
result = 0
# Iterate through array nums[]
for i in range(N):
# Bits set in nums[i] are
# also set in result
result |= nums[i]
# Calculate prefix_sum
prefix_sum += nums[i]
# Bits set in prefix_sum
# are also set in result
result |= prefix_sum
# Return the result
return result
#l=[]
def OR(a, n):
ans = a[0]
for i in range(1, n):
ans |= a[i]
#l.append(ans)
return ans
#print(prime(12345678987766))
def toString(List):
return ''.join(List)
# Function to print permutations of string
# This function takes three parameters:
# 1. String
# 2. Starting index of the string
# 3. Ending index of the string.
p=[]
def permute(a, l, r):
if l == r:
p.append(toString(a))
else:
for i in range(l, r + 1):
a[l], a[i] = a[i], a[l]
permute(a, l + 1, r)
a[l], a[i] = a[i], a[l] # backtrack
# Function to find square root of
# given number upto given precision
def squareRoot(number, precision):
start = 0
end, ans = number, 1
# For computing integral part
# of square root of number
while (start <= end):
mid = int((start + end) / 2)
if (mid * mid == number):
ans = mid
break
# incrementing start if integral
# part lies on right side of the mid
if (mid * mid < number):
start = mid + 1
# decrementing end if integral part
# lies on the left side of the mid
else:
end = mid - 1
# For computing the fractional part
# of square root upto given precision
increment = 0.1
for i in range(0, precision):
while (ans * ans <= number):
ans += increment
# loop terminates when ans * ans > number
ans = ans - increment
increment = increment / 10
return ans
#for i in range(200):
# if sumofdigits(i)==10:
#print(i)
def main():
n=int(input())
arr=list(map(int,input().split()))
if 1 not in arr:
print(0)
exit()
one,zero=[],[]
for i in range(n):
if arr[i]==1:
one.append(i)
else:
zero.append(i)
n=len(one)
m=len(zero)
DP=[0]*(m+1)
for i in range(n-1,-1,-1):
DP1=[]
v=10**9
for j in range(len(DP)-2,-1,-1):
v=min(v,abs(one[i]-zero[j])+DP[j+1])
DP1.append(v)
DP=DP1.copy()
DP.reverse()
print(min(DP))
if __name__ == '__main__':
main()
``` | instruction | 0 | 59,983 | 14 | 119,966 |
Yes | output | 1 | 59,983 | 14 | 119,967 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
#sys.setrecursionlimit(100000)
#^^^TAKE CARE FOR MEMORY LIMIT^^^
import random
def main():
pass
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def binary(n):
return (bin(n).replace("0b", ""))
def decimal(s):
return (int(s, 2))
def pow2(n):
p = 0
while (n > 1):
n //= 2
p += 1
return (p)
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
l.append(i)
n = n / i
if n > 2:
l.append(int(n))
return (l)
def isPrime(n):
if (n == 1):
return (False)
else:
root = int(n ** 0.5)
root += 1
for i in range(2, root):
if (n % i == 0):
return (False)
return (True)
def maxPrimeFactors(n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
def countcon(s, i):
c = 0
ch = s[i]
for i in range(i, len(s)):
if (s[i] == ch):
c += 1
else:
break
return (c)
def lis(arr):
n = len(arr)
lis = [1] * n
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
maximum = 0
for i in range(n):
maximum = max(maximum, lis[i])
return maximum
def isSubSequence(str1, str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j < m and i < n:
if str1[j] == str2[i]:
j = j + 1
i = i + 1
return j == m
def maxfac(n):
root = int(n ** 0.5)
for i in range(2, root + 1):
if (n % i == 0):
return (n // i)
return (n)
def p2(n):
c=0
while(n%2==0):
n//=2
c+=1
return c
def seive(n):
primes=[True]*(n+1)
primes[1]=primes[0]=False
i=2
while(i*i<=n):
if(primes[i]==True):
for j in range(i*i,n+1,i):
primes[j]=False
i+=1
pr=[]
for i in range(0,n+1):
if(primes[i]):
pr.append(i)
return pr
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def denofactinverse(n,m):
fac=1
for i in range(1,n+1):
fac=(fac*i)%m
return (pow(fac,m-2,m))
def numofact(n,m):
fac=1
for i in range(1,n+1):
fac=(fac*i)%m
return(fac)
def sod(n):
s=0
while(n>0):
s+=n%10
n//=10
return s
n=int(input())
l=list(map(int,input().split()))
o,z=[],[]
for i in range(0,n):
if(l[i]):
o.append(i)
else:
z.append(i)
inF=10**20
dp=[[inF]*(len(z)+1) for i in range(0,len(o)+1)]
for i in range(0,len(z)+1):
dp[0][i]=0
for i in range(1,len(o)+1):
for j in range(1,len(z)+1):
dp[i][j]=min(dp[i][j-1],abs(o[i-1]-z[j-1])+dp[i-1][j-1])
#for i in dp:
# print(*i)
print(dp[-1][-1])
``` | instruction | 0 | 59,984 | 14 | 119,968 |
Yes | output | 1 | 59,984 | 14 | 119,969 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Submitted Solution:
```
def do():
n = int(input())
dat = list(map(int, input().split()))
dat0, dat1 = [], []
for i in range(n):
if dat[i] == 0: dat0.append(i)
else: dat1.append(i)
if len(dat1) == 0:
print(0)
return
dp = [None] * len(dat1)
dp[0] = 10**18
for ind0 in range(len(dat0)):
for ind1 in range(len(dat1)-1, 0, -1):
curcost = abs(dat0[ind0] - dat1[ind1])
if dp[ind1 - 1] is None: continue
if dp[ind1] is None: dp[ind1] = 10**18
dp[ind1] = min(dp[ind1], dp[ind1 - 1] + curcost)
curcost = abs(dat0[ind0] - dat1[0])
dp[0] = min(curcost, dp[0])
print(dp[-1])
do()
``` | instruction | 0 | 59,985 | 14 | 119,970 |
Yes | output | 1 | 59,985 | 14 | 119,971 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Submitted Solution:
```
from sys import stdin, stdout
from collections import *
from math import gcd, ceil, floor
def st():
return list(stdin.readline().strip())
def li():
return list(map(int, stdin.readline().split()))
def mp():
return map(int, stdin.readline().split())
def inp():
return int(stdin.readline())
def pr(n):
return stdout.write(str(n) + "\n")
mod = 1000000007
INF = float('inf')
Y = "YES"
N = "NO"
def solve():
# solve here
N = int(input())
c = li()
pos = []
per = []
for i in range(N):
if c[i] == 0:
pos.append(i)
else:
per.append(i)
n = len(pos)
m = len(per)
dp = [[INF for i in range(m + 1)] for j in range(n + 1)]
dp[0][0] = 0
for i in range(n):
for j in range(m):
dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])
dp[i + 1][j + 1] = min(dp[i + 1][j + 1],
dp[i][j] + abs(pos[i] - per[j]))
print(min(dp[i][m] for i in range(n + 1)))
for test in range(1):
solve()
``` | instruction | 0 | 59,986 | 14 | 119,972 |
Yes | output | 1 | 59,986 | 14 | 119,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
x=[]
z=[]
for i in range(n):
if l[i]==0:
x.append(i)
else:
z.append(i)
ans=0
for i in z:
t=n
i1=None
for j in x:
if abs(i-j)<t:
t=abs(i-j)
i1=j
x.remove(i1)
ans+=t
print(ans)
``` | instruction | 0 | 59,987 | 14 | 119,974 |
No | output | 1 | 59,987 | 14 | 119,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Submitted Solution:
```
def listRightIndex(alist, value):
return alist[-1::-1].index(value)
import math
n=int(input())
arr=list(map(int, input().split()))
arr2=arr.copy()
arr2=arr2[::-1]
count=0
count2=0
for i in range(n):
if arr[i]==1:
prevlist=arr[:i]
nextlist=arr[i+1:]
#print(prevlist,nextlist)
try:
prevind=listRightIndex(prevlist,0)
except:
prevind=math.inf
try:
nextind=nextlist.index(0)
except:
nextind=math.inf
#print(prevind, nextind)
if prevind>nextind:
arr[i],arr[nextind+i+1]=None,2
count+=abs(nextind+1)
else:
arr[i],arr[i-prevind-1]=None,2
count+=abs(prevind+1)
#print(arr)
for i in range(n):
if arr2[i]==1:
prevlist=arr2[:i]
nextlist=arr2[i+1:]
#print(prevlist,nextlist)
try:
prevind=listRightIndex(prevlist,0)
except:
prevind=math.inf
try:
nextind=nextlist.index(0)
except:
nextind=math.inf
#print(prevind, nextind)
if prevind>nextind:
arr2[i],arr2[nextind+i+1]=None,2
count2+=abs(nextind+1)
else:
arr2[i],arr2[i-prevind-1]=None,2
count2+=abs(prevind+1)
#print(arr2)
print(min(count,count2))
``` | instruction | 0 | 59,988 | 14 | 119,976 |
No | output | 1 | 59,988 | 14 | 119,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Submitted Solution:
```
n=int(input())
A=list(map(int,input().split()))
ans=0
for i in range(n):
if A[i]==1:
flagj=False
flagk=False
for j in range(i+1,n):
if A[j]==0:
flagj=True
break
for k in range(i-1,-1,-1):
if A[k]==0:
flagk=True
break
if flagj and flagk:
if j-i>i-k:
A[k]=3
ans+=i-k
else:
A[j]=3
ans+=j-i
elif flagj and not flagk:
ans+=j-i
A[j]=3
else:
ans+=i-k
A[k]=3
A[i]=2
print(ans)
``` | instruction | 0 | 59,989 | 14 | 119,978 |
No | output | 1 | 59,989 | 14 | 119,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 β€ n β€ 5000) β the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer β the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Submitted Solution:
```
from math import fabs
n = int(input())
a = list(map(int, input().split()))
isempt = []
toseat = []
res = 0
for i in range(n):
if a[i] == 0 and toseat:
while toseat and isempt:
res += fabs(isempt[-1] - toseat[0])
toseat = toseat[1:]
isempt = isempt[:-1]
if toseat:
res += i - toseat[0]
toseat = toseat[1:]
else: isempt.append(i)
elif a[i] == 0: isempt.append(i)
else: toseat.append(i)
#print(isempt)
#print(toseat)
while toseat:
res += fabs(isempt[-1] - toseat[0])
toseat = toseat[1:]
isempt = isempt[:-1]
print(int(res))
``` | instruction | 0 | 59,990 | 14 | 119,980 |
No | output | 1 | 59,990 | 14 | 119,981 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps. | instruction | 0 | 60,071 | 14 | 120,142 |
Tags: data structures, implementation
Correct Solution:
```
n, t = int(input()), list(map(int, input().split()))
p, s, r = [0] * n, [0] * n, t[0]
for i in range(n - 1):
j = i + 1
x = t[j]
if x > r: r = x
else:
while t[i] < x: s[j], i = max(s[j], s[i]), p[i]
p[j] = i
s[j] += 1
print(max(s))
# Made By Mostafa_Khaled
``` | output | 1 | 60,071 | 14 | 120,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps. | instruction | 0 | 60,072 | 14 | 120,144 |
Tags: data structures, implementation
Correct Solution:
```
n = int(input())
A = list(map(int,input().strip().split()))[::-1]
p = 0
p_max = 0
X = []
for i in A:
# print(X)
while(len(X)>0 and X[-1][0]<i):
p = max((p+1,X[-1][1]))
X.pop()
X.append((i,p))
if p>p_max:
p_max = p
p=0
print(p_max)
``` | output | 1 | 60,072 | 14 | 120,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps. | instruction | 0 | 60,073 | 14 | 120,146 |
Tags: data structures, implementation
Correct Solution:
```
n = int(input())
aa = list(map(int,input().split()))
live = []
ans=0
for i in range(n-1,-1,-1):
c = 0
while len(live)!=0 and live[-1][0]<aa[i]:
c = max(c+1,live[-1][1])
live.pop()
if c>ans: ans =c
live.append((aa[i],c))
print(ans)
``` | output | 1 | 60,073 | 14 | 120,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps. | instruction | 0 | 60,074 | 14 | 120,148 |
Tags: data structures, implementation
Correct Solution:
```
N=int(input())
psychos=list(map(int, input().split(" ")))
time_of_death=[0 for i in range(N)]
stack=[(psychos[0], 0)]
for index, p in enumerate(psychos):
if index==0:
continue
if p<stack[-1][0]:
stack.append((p, 1))
time_of_death[index]=1
elif p>stack[-1][0]:
max_time=-1
while stack!=[] and p>stack[-1][0]:
max_time=max(max_time, stack[-1][1])
del stack[-1]
if stack==[]:
# will never die, no bigger psychos to left
stack.append((p, 0))
time_of_death[index]=0
else:
# will die, bigger psycho to left
stack.append((p, max_time+1))
time_of_death[index]=max_time+1
print(max(time_of_death))
'''
7
15 9 5 10 7 11 14
'''
``` | output | 1 | 60,074 | 14 | 120,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps. | instruction | 0 | 60,075 | 14 | 120,150 |
Tags: data structures, implementation
Correct Solution:
```
n = int(input())
A = [int(i) for i in input().split()]
ans = 0
st = [0]
tdeath = [-1 for i in range(n)]
for i in range(1, n):
tdeath[i] = 0
while len(st) > 0 and A[st[-1]] < A[i]:
tdeath[i] = max(tdeath[i], tdeath[st[-1]]+1)
st.pop()
if len(st)==0:
tdeath[i] = -1
st.append(i)
ans = max(ans, tdeath[i]+1)
print(ans)
``` | output | 1 | 60,075 | 14 | 120,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps. | instruction | 0 | 60,076 | 14 | 120,152 |
Tags: data structures, implementation
Correct Solution:
```
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
# from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
from sys import stdin
input = stdin.readline
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,6)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
from sys import stdin
input = stdin.readline
n = int(input())
ans = 0
stk = []
for v in map(int, input().split()):
last = 0
# print(stk)
while len(stk) and stk[-1][0] < v and stk[-1][1]:
last = max(last, stk[-1][1])
del stk[-1]
# print("INTERMEDIATE",stk)
if not len(stk) or stk[-1][0] < v:
stk.append((v, 0))
else:
stk.append((v, last + 1)); ans = max(ans, last + 1)
# print(stk)
print(ans)
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
``` | output | 1 | 60,076 | 14 | 120,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps. | instruction | 0 | 60,077 | 14 | 120,154 |
Tags: data structures, implementation
Correct Solution:
```
def main():
from bisect import bisect_left as bl, bisect_right as br, insort
import sys,math
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
out = sys.stdout.write
# sys.setrecursionlimit(100000)
INF = float("INF")
mod = int(1e9)+7
n=int(data())
l=mdata()
cnt=0
m=0
max1=0
X=[]
for i in l[::-1]:
while len(X) and X[-1][0]<i:
m=max(m+1,X[-1][1])
X.pop()
X.append([i, m])
if m>max1:
max1=m
m=0
print(max1)
if __name__ == '__main__':
main()
``` | output | 1 | 60,077 | 14 | 120,155 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps. | instruction | 0 | 60,078 | 14 | 120,156 |
Tags: data structures, implementation
Correct Solution:
```
from sys import stdin,stdout
def main(n, a):
ans = 0
top = 0
t = [0 for i in range(n)]
f = [0 for i in range(n)]
for i in range(n - 1, -1, -1):
tt = 0
while top > 0 and a[t[top - 1]] < a[i]:
top -= 1
tt = max(tt + 1, f[t[top]])
f[i] = tt
t[top] = i
top += 1
return max(f)
stdout.write('{}\n'.format(main(int(stdin.readline().strip()), list(map(int, input().split(' '))))))
``` | output | 1 | 60,078 | 14 | 120,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
Submitted Solution:
```
n, t = int(input()), list(map(int, input().split()))
p, s, r = [0] * n, [0] * n, t[0]
for i in range(n - 1):
j = i + 1
x = t[j]
if x > r: r = x
else:
while t[i] < x: s[j], i = max(s[j], s[i]), p[i]
p[j] = i
s[j] += 1
print(max(s))
``` | instruction | 0 | 60,079 | 14 | 120,158 |
Yes | output | 1 | 60,079 | 14 | 120,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
Submitted Solution:
```
n = int(input())
ans = 0
stk = []
for v in map(int, input().split()):
last = 0
while len(stk) and stk[-1][0] < v and stk[-1][1]:
last = max(last, stk[-1][1])
del stk[-1]
if not len(stk) or stk[-1][0] < v:
stk.append((v, 0))
else:
stk.append((v, last + 1)); ans = max(ans, last + 1)
print(ans)
``` | instruction | 0 | 60,080 | 14 | 120,160 |
Yes | output | 1 | 60,080 | 14 | 120,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
Submitted Solution:
```
# author : Tapan Goyal
# MNIT Jaipur
import math
import bisect
import itertools
import sys
I=lambda : sys.stdin.readline()
one=lambda : int(I())
more=lambda : map(int,I().split())
linput=lambda : list(more())
mod=10**9 +7
'''fact=[1]*100001
ifact=[1]*100001
for i in range(1,100001):
fact[i]=((fact[i-1])*i)%mod
ifact[i]=((ifact[i-1])*pow(i,mod-2,mod))%mod
def ncr(n,r):
return (((fact[n]*ifact[n-r])%mod)*ifact[r])%mod
def npr(n,r):
return (((fact[n]*ifact[n-r])%mod))
'''
def merge(a,b):
i=0;j=0
c=0
ans=[]
while i<len(a) and j<len(b):
if a[i]<b[j]:
ans.append(a[i])
i+=1
else:
ans.append(b[j])
c+=len(a)-i
j+=1
ans+=a[i:]
ans+=b[j:]
return ans,c
def mergesort(a):
if len(a)==1:
return a,0
mid=len(a)//2
left,left_inversion=mergesort(a[:mid])
right,right_inversion=mergesort(a[mid:])
m,c=merge(left,right)
c+=(left_inversion+right_inversion)
return m,c
def is_prime(num):
if num == 1: return False
if num == 2: return True
if num == 3: return True
if num%2 == 0: return False
if num%3 == 0: return False
t = 5
a = 2
while t <= int(math.sqrt(num)):
if num%t == 0: return False
t += a
a = 6 - a
return True
def ceil(a,b):
return (a+b-1)//b
#/////////////////////////////////////////////////////////////////////////////////////////////////
if __name__ == "__main__":
n=one()
a=linput()
st=[]
ans=0
for i in range(n):
cur=0
while st and st[-1][0]<a[-i-1]:
cur+=1
cur=max(cur,st[-1][1])
st.pop()
st.append([a[-i-1],cur])
ans=max(cur,ans)
print(ans)
``` | instruction | 0 | 60,081 | 14 | 120,162 |
Yes | output | 1 | 60,081 | 14 | 120,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
Submitted Solution:
```
from math import sqrt,ceil,gcd
from collections import defaultdict
def modInverse(b,m):
g = gcd(b, m)
if (g != 1):
# print("Inverse doesn't exist")
return -1
else:
# If b and m are relatively prime,
# then modulo inverse is b^(m-2) mode m
return pow(b, m - 2, m)
def sol(n,m,rep):
r = 1
for i in range(2,n+1):
j = i
while j%2 == 0 and rep>0:
j//=2
rep-=1
r*=j
r%=m
return r
def solve():
n = int(input())
l = list(map(int,input().split()))
st = []
ans = 0
hash = defaultdict(lambda : -1)
for i in range(n):
hash[i] = 0
while st!=[] and l[st[-1]]<l[i]:
z = st.pop()
hash[i] = max(hash[i],hash[z]+1)
if st == []:
hash[i] = -1
st.append(i)
ans = max(ans,hash[i]+1)
print(ans)
# t = int(input())
# for _ in range(t):
solve()
``` | instruction | 0 | 60,082 | 14 | 120,164 |
Yes | output | 1 | 60,082 | 14 | 120,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
Submitted Solution:
```
def main():
from bisect import bisect_left as bl, bisect_right as br, insort
import sys,math
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
out = sys.stdout.write
# sys.setrecursionlimit(100000)
INF = float("INF")
mod = int(1e9)+7
n=int(data())
l=mdata()
m=0
max1=l[0]
cnt=0
for i in range(1,n):
if l[i]>l[i-1]:
m=max(m,cnt)
cnt+=1
if l[i]>max1:
max1=l[i]
cnt=0
else:
cnt=max(1,cnt)
m=max(m,cnt)
cnt=1
m=max(m,cnt)
print(m)
if __name__ == '__main__':
main()
``` | instruction | 0 | 60,083 | 14 | 120,166 |
No | output | 1 | 60,083 | 14 | 120,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
c=-1
ans=0
f=0
while True:
b=[]
d=[]
for i in range(len(a)):
if (i+1)<len(a):
if a[i]>a[i+1]:
f=1
b.append(a[i])
d.append(a[i+1])
if f:
res = filter(lambda i: i not in d, b)
a=list(res)
ans+=1
if c==len(a):
break
c=len(b)
f=0
else:
break
print(ans)
``` | instruction | 0 | 60,084 | 14 | 120,168 |
No | output | 1 | 60,084 | 14 | 120,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
Input
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
Output
Print the number of steps, so that the line remains the same afterward.
Examples
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
Note
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
Submitted Solution:
```
n = int(input())
a = list(map(int,input().split()))
b = [0]; curr = a[0];
for i in range(1,len(a)):
if a[i-1]>a[i]:
continue
if a[i-1]<=a[i]:
if a[i]<curr:
b[-1] += 1
else:
curr = a[i]
b.append(1)
print(max(b))
``` | instruction | 0 | 60,085 | 14 | 120,170 |
No | output | 1 | 60,085 | 14 | 120,171 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,238 | 14 | 120,476 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
from bisect import bisect
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
n,a,b,t=in_arr()
s=[1+b*int(i=='w') for i in raw_input().strip()]
dp1=[]
dp2=[0]
sm=0
for i in range(n-1,-1,-1):
sm+=s[i]
dp1.append(sm)
sm+=a
sm=0
for i in range(1,n):
sm+=s[i]
dp2.append(sm)
sm+=a
sm=0
ans=0
for i in range(n):
sm+=s[i]
if sm<=t:
#print ans,i+1
ans=max(ans,i+1)
temp=t-sm-(a*(i+1))
if temp<0:
sm+=a
continue
#print i+1,temp,bisect(dp,temp),dp
ans=max(ans,i+1+min(n-i-1,bisect(dp1,temp)))
sm+=a
sm=s[0]+a
#print ans
for i in range(n-1,0,-1):
sm+=s[i]
if sm<=t:
#print n-1-i+2
ans=max(ans,n-1-i+2)
temp=t-sm-((n-1-i+2)*a)
if temp<0:
sm+=a
continue
#print i,n-1-i+2,min(i-1,bisect(dp2,temp))-1
ans=max(ans,n-1-i+2+min(i-1,bisect(dp2,temp))-1)
sm+=a
pr_num(ans)
``` | output | 1 | 60,238 | 14 | 120,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,239 | 14 | 120,478 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
#! /usr/bin/env python3
def main():
n, a, b, t = map(int, input().split())
oris = input()
def get_time(front, rear, count_rot):
span = front - rear
offset = min(front, -rear)
return span, span * a + (span + 1) + offset * a + count_rot * b
front = rear = span = count_rot = new_count_rot = time = 0
has_one = False
for i in range(0, -n, -1):
if oris[i] == 'w':
new_count_rot += 1
new_span, new_time = get_time(front, i, new_count_rot)
if new_time > t:
break
has_one = True
span, time, rear, count_rot = new_span, new_time, i, new_count_rot
if not has_one:
return 0
maxi = max_span = n - 1
while front < maxi and rear <= 0 and span != max_span:
front += 1
if oris[front] == 'w':
count_rot += 1
while True:
new_span, time = get_time(front, rear, count_rot)
if time <= t:
break
if oris[rear] == 'w':
count_rot -= 1
rear += 1
if rear > 0:
return span + 1
span = max(new_span, span)
return span + 1
print(main())
``` | output | 1 | 60,239 | 14 | 120,479 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,240 | 14 | 120,480 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
def main():
n, a, b, t = map(int, input().split())
b += 1
l = [b if char == "w" else 1 for char in input()]
t -= sum(l) - a * (n + 2)
hi, n2 = n, n * 2
n3 = n2 + 1
lo = res = 0
l *= 2
while lo <= n and hi < n2:
t -= l[hi]
hi += 1
while (hi - lo + (hi if hi < n3 else n3)) * a > t or lo < hi - n:
t += l[lo]
lo += 1
n3 -= 1
if res < hi - lo:
res = hi - lo
if res == n:
break
print(res)
if __name__ == '__main__':
main()
``` | output | 1 | 60,240 | 14 | 120,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,241 | 14 | 120,482 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
def main():
n, a, b, t = map(int, input().split())
b += 1
l = [b if char == "w" else 1 for char in input()]
t -= sum(l) - a * (n + 2)
hi, n2 = n, n * 2
n21 = n2 + 1
lo = res = 0
l *= 2
while lo <= n and hi < n2:
t -= l[hi]
hi += 1
b = hi - n
while lo < b or (hi - lo + (hi if hi < n21 - lo else n21 - lo)) * a > t:
t += l[lo]
lo += 1
if res < hi - lo:
res = hi - lo
if res == n:
break
print(res)
if __name__ == '__main__':
main()
``` | output | 1 | 60,241 | 14 | 120,483 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,242 | 14 | 120,484 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
def main():
n, a, b, t = map(int, input().split())
b += 1
l = [b if char == "w" else 1 for char in input()]
t -= sum(l) - a * (n + 2)
hi, n2 = n, n * 2
n3 = n2 + 1
lo = res = 0
l *= 2
while lo <= n and hi < n2:
t -= l[hi]
hi += 1
b = hi - n
while lo < b or (hi - lo + (hi if hi < n3 else n3)) * a > t:
t += l[lo]
lo += 1
n3 -= 1
if res < hi - lo:
res = hi - lo
if res == n:
break
print(res)
if __name__ == '__main__':
main()
``` | output | 1 | 60,242 | 14 | 120,485 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,243 | 14 | 120,486 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
import sys
INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
"""
Facts and Data representation
Constructive? Top bottom up down
"""
n, a, b, T = I()
s = input()
A = []
B = []
time = 0
d = {'h': 1, 'w': b + 1}
for i in range(n):
time += d[s[i]]
A.append(time)
time += a
time = 0
for i in range(n - 1, 0, -1):
time += a
time += d[s[i]]
B.append(time)
ans = 0
# print(A, B)
for i in range(n):
time = A[i]
if time > T:
break
l = br(B, T - time - i * a)
ans = max(ans, i + 1 + l)
B = [A[0]] + [A[0] + i for i in B]
A = [A[i] - (A[0]) for i in range(1, n)]
# print(A, B)
for i in range(n):
time = B[i]
if time > T:
break
l = br(A, T - time - i * a)
ans = max(ans, i + 1 + l)
print(min(n, ans))
``` | output | 1 | 60,243 | 14 | 120,487 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,244 | 14 | 120,488 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
def main():
n, a, b, t = map(int, input().split())
b += 1
l = [b if char == "w" else 1 for char in input()]
t -= sum(l) - a * (n + 2)
hi, n2 = n, n * 2
n3 = n2 + 1
lo = res = 0
l *= 2
while lo <= n and hi < n2:
t -= l[hi]
hi += 1
while (hi - lo + (hi if hi < n3 else n3)) * a > t or lo < hi - n:
t += l[lo]
lo += 1
n3 -= 1
if res < hi - lo:
res = hi - lo
if res == n:
break
print(res)
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled
``` | output | 1 | 60,244 | 14 | 120,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,245 | 14 | 120,490 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
# [https://codeforces.com/contest/650/submission/16709913]
(n, a, b, t) = map(int, input().split())
b += 1
l = [b if char == "w" else 1 for char in input()]
t -= sum(l) - a * (n + 2)
hi = n
n2 = n * 2
n3 = n2 + 1
lo = 0
res = 0
l *= 2
while lo <= n and hi < n2:
t -= l[hi]
hi += 1
while (hi - lo + (hi if hi < n3 else n3)) * a > t or lo < hi - n:
t += l[lo]
lo += 1
n3 -= 1
if res < hi - lo:
res = hi - lo
if res == n:
break
print(res)
``` | output | 1 | 60,245 | 14 | 120,491 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. | instruction | 0 | 60,246 | 14 | 120,492 |
Tags: binary search, brute force, dp, two pointers
Correct Solution:
```
read = lambda: map(int, input().split())
per = lambda L, R: R - L - 1 + min(R - n - 1, n - L)
n, a, b, T = read()
f = [1 + (i == 'w') * b for i in input()] * 2
L, R = 0, n
ans = 0
cur = sum(f) // 2
while L <= n and R < n * 2:
cur += f[R]; R += 1
while R - L > n or cur + per(L, R) * a > T:
cur -= f[L]; L += 1
ans = max(ans, R - L)
print(ans)
``` | output | 1 | 60,246 | 14 | 120,493 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
def main():
n, a, b, t = map(int, input().split())
b += 1
l = [b if char == "w" else 1 for char in input()]
t -= sum(l) - a * (n + 2)
hi, n2 = n, n * 2
n3 = n2 + 1
lo = res = 0
l *= 2
while lo <= n and hi < n2:
t -= l[hi]
hi += 1
while (hi - lo + (hi if hi < n3 else n3)) * a > t:
t += l[lo]
lo += 1
n3 -= 1
if res < hi - lo:
res = hi - lo
if res >= n:
res = n
break
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 60,247 | 14 | 120,494 |
Yes | output | 1 | 60,247 | 14 | 120,495 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
def main():
n, a, b, t = map(int, input().split())
b += 1
l = [b if char == "w" else 1 for char in input()]
t -= sum(l) - a * (n + 2)
hi, n2 = n, n * 2
n21 = n2 + 1
lo = res = 0
l *= 2
while lo <= n and hi < n2:
t -= l[hi]
hi += 1
b = hi - n
while lo < b or (hi - lo + min(hi, n21 - lo)) * a > t:
t += l[lo]
lo += 1
if res < hi - lo:
res = hi - lo
if res == n:
break
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 60,248 | 14 | 120,496 |
Yes | output | 1 | 60,248 | 14 | 120,497 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
def main():
n, a, b, t = map(int, input().split())
a1 = a + 1
b += a1
l, res = [b if c == "w" else a1 for c in input()], []
l[0] = x = l[0] - a
if t <= x:
print(int(t == x))
return
f = res.append
for dr in 0, 1:
if dr:
l[1:] = l[-1:-n:-1]
tot = t
for hi, x in enumerate(l):
tot -= x
if tot < 0:
break
else:
print(n)
return
f(hi)
tot += x
hi -= 1
tot -= hi * a
lo = n
while True:
while lo > 0 <= tot:
lo -= 1
tot -= l[lo]
f(n + hi - lo)
if not (lo and hi):
break
while tot <= 0 < hi:
tot += l[hi] + a
hi -= 1
print(max(res))
if __name__ == '__main__':
main()
``` | instruction | 0 | 60,249 | 14 | 120,498 |
Yes | output | 1 | 60,249 | 14 | 120,499 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
n, a, b, T = map(int, input().split())
s = input()
prefsum = [0] * n
suffsum = [0] * n
for i in range(n):
prefsum[i] = 1 if s[i] == 'h' else b + 1
if i > 0:
prefsum[i] += a + prefsum[i - 1]
suffsum[-1] = a
for i in range(n - 1, -1, -1):
suffsum[i] += 1 if s[i] == 'h' else b + 1
if i + 1 < n:
suffsum[i] += a + suffsum[i + 1]
res = 0
# go right and come back left
l = 1
for r in range(n):
l = max(l, r + 1)
while l < n and suffsum[l] + r * a + prefsum[r] > T:
l += 1
if prefsum[r] > T:
break
res = max(res, r + 1 + n - l)
# go left and come back right
l = 1
for r in range(n):
l = max(l, r + 1)
while l < n and suffsum[l] + (n - l) * a + prefsum[r] > T:
l += 1
if prefsum[r] > T:
break
res = max(res, r + 1 + n - l)
# go in a single direction
for r in range(n):
# right
if prefsum[r] <= T:
res = max(res, r + 1)
# left
if r > 0 and suffsum[r] + prefsum[0] <= T:
res = max(res, n - r + 1)
print(res)
``` | instruction | 0 | 60,250 | 14 | 120,500 |
Yes | output | 1 | 60,250 | 14 | 120,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
n,a,b,t=map(int, input().split(" "))
ch=input()
i=0
s=0
k=0
while (i<n):
if ch[i]=='w':
s=s+b
if s>t:
break
s=s+1
if s>t:
break
k=k+1
s=s+a
if s>t:
break
i=i+1
print(k)
``` | instruction | 0 | 60,251 | 14 | 120,502 |
No | output | 1 | 60,251 | 14 | 120,503 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
from sys import stdin,stdout
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
for _ in range(1):#nmbr()):
n,sw,turn,t=lst()
s=list(input())
ans=0
a=[0]*n
if s[0]=='w':a[0]=turn+1
for i in range(1,n):
if s[i]=='h':
a[i]=a[i-1]+1
else:a[i]=a[i-1]+1+turn
for i in range(n):
a[i]+=i*sw
ans=n
# print(a)
for i in range(n):
if a[i]>t:
ans=i
break
print(ans)
``` | instruction | 0 | 60,252 | 14 | 120,504 |
No | output | 1 | 60,252 | 14 | 120,505 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
#! /usr/bin/env python3
def main():
# n, a, b, t = map(int, input().split())
# oris = input()
s1 = "5 2 4 1000"
s2 = "hhwhh"
n, a, b, t = map(int, s1.split())
oris = s2
def get_time(front, rear, count_rot):
span = front - rear
offset = min(front, -rear)
return span, span * a + (span + 1) + offset * a + count_rot * b
front = rear = span = count_rot = new_count_rot = time = 0
has_one = False
for i in range(0, -n, -1):
if oris[i] == 'w':
new_count_rot += 1
new_span, new_time = get_time(front, i, new_count_rot)
if new_time > t:
break
has_one = True
span, time, rear, count_rot = new_span, new_time, i, new_count_rot
if not has_one:
return 0
maxi = max_span = n - 1
while front < maxi and rear <= 0 and span != max_span:
front += 1
if oris[front] == 'w':
count_rot += 1
while True:
new_span, time = get_time(front, rear, count_rot)
if time <= t:
break
if oris[rear] == 'w':
count_rot -= 1
rear += 1
if rear > 0:
return span + 1
span = max(new_span, span)
return span + 1
print(main())
``` | instruction | 0 | 60,253 | 14 | 120,506 |
No | output | 1 | 60,253 | 14 | 120,507 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
import sys
INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
"""
Facts and Data representation
Constructive? Top bottom up down
"""
n, a, b, T = I()
s = input()
A = []
B = []
time = 0
d = {'h': 0, 'w': b}
for i in range(n):
time += d[s[i]]
time += 1
A.append(time)
time += a
time = 0
for i in range(n - 1, 0, -1):
time += a
time += d[s[i]]
time += 1
B.append(time)
ans = 0
# print(A, B)
for i in range(n):
time = A[i]
if time > T:
break
l = bl(B, T - time - i * a)
ans = max(ans, i + 1 + l)
B = [A[0]] + B
A.pop(0)
for i in range(n):
time = B[i]
if time > T:
break
l = bl(A, T - time - i * a)
ans = max(ans, i + 1 + l)
print(min(n, ans))
``` | instruction | 0 | 60,254 | 14 | 120,508 |
No | output | 1 | 60,254 | 14 | 120,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.
Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
Input
The first line contains two integers n and k (1 β€ n β€ 105, 1 β€ k β€ 109) β the number of different pebble types and number of pebbles Anastasia can place in one pocket.
The second line contains n integers w1, w2, ..., wn (1 β€ wi β€ 104) β number of pebbles of each type.
Output
The only line of output contains one integer β the minimum number of days Anastasia needs to collect all the pebbles.
Examples
Input
3 2
2 3 4
Output
3
Input
5 4
3 1 8 9 7
Output
5
Note
In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type β on the second day, and of third type β on the third day.
Optimal sequence of actions in the second sample case:
* In the first day Anastasia collects 8 pebbles of the third type.
* In the second day she collects 8 pebbles of the fourth type.
* In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.
* In the fourth day she collects 7 pebbles of the fifth type.
* In the fifth day she collects 1 pebble of the second type. | instruction | 0 | 60,284 | 14 | 120,568 |
Tags: implementation, math
Correct Solution:
```
n, k = map(int, input().split())
w = list(map(int, input().split()))
for i in range(n):
w[i] = w[i] // k + (1 if w[i] % k > 0 else 0)
t = sum(w)
print(t // 2 + t % 2)
``` | output | 1 | 60,284 | 14 | 120,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.
Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
Input
The first line contains two integers n and k (1 β€ n β€ 105, 1 β€ k β€ 109) β the number of different pebble types and number of pebbles Anastasia can place in one pocket.
The second line contains n integers w1, w2, ..., wn (1 β€ wi β€ 104) β number of pebbles of each type.
Output
The only line of output contains one integer β the minimum number of days Anastasia needs to collect all the pebbles.
Examples
Input
3 2
2 3 4
Output
3
Input
5 4
3 1 8 9 7
Output
5
Note
In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type β on the second day, and of third type β on the third day.
Optimal sequence of actions in the second sample case:
* In the first day Anastasia collects 8 pebbles of the third type.
* In the second day she collects 8 pebbles of the fourth type.
* In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.
* In the fourth day she collects 7 pebbles of the fifth type.
* In the fifth day she collects 1 pebble of the second type. | instruction | 0 | 60,285 | 14 | 120,570 |
Tags: implementation, math
Correct Solution:
```
_, cap = (int(x) for x in input().split())
items = [int(x) for x in input().split()]
res = 0
for item in items:
times = item//cap
res += times
if times*cap<item: res += 1
days = res // 2
print(days if days*2 == res else days + 1)
``` | output | 1 | 60,285 | 14 | 120,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.
Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
Input
The first line contains two integers n and k (1 β€ n β€ 105, 1 β€ k β€ 109) β the number of different pebble types and number of pebbles Anastasia can place in one pocket.
The second line contains n integers w1, w2, ..., wn (1 β€ wi β€ 104) β number of pebbles of each type.
Output
The only line of output contains one integer β the minimum number of days Anastasia needs to collect all the pebbles.
Examples
Input
3 2
2 3 4
Output
3
Input
5 4
3 1 8 9 7
Output
5
Note
In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type β on the second day, and of third type β on the third day.
Optimal sequence of actions in the second sample case:
* In the first day Anastasia collects 8 pebbles of the third type.
* In the second day she collects 8 pebbles of the fourth type.
* In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.
* In the fourth day she collects 7 pebbles of the fifth type.
* In the fifth day she collects 1 pebble of the second type. | instruction | 0 | 60,286 | 14 | 120,572 |
Tags: implementation, math
Correct Solution:
```
n, k = [int(i) for i in input().split()]
w = [int(i) for i in input().split()]
tot = 0
for wi in w:
tot += (wi+k-1)//k
ans = (tot+1)//2
print(ans)
``` | output | 1 | 60,286 | 14 | 120,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.
Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
Input
The first line contains two integers n and k (1 β€ n β€ 105, 1 β€ k β€ 109) β the number of different pebble types and number of pebbles Anastasia can place in one pocket.
The second line contains n integers w1, w2, ..., wn (1 β€ wi β€ 104) β number of pebbles of each type.
Output
The only line of output contains one integer β the minimum number of days Anastasia needs to collect all the pebbles.
Examples
Input
3 2
2 3 4
Output
3
Input
5 4
3 1 8 9 7
Output
5
Note
In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type β on the second day, and of third type β on the third day.
Optimal sequence of actions in the second sample case:
* In the first day Anastasia collects 8 pebbles of the third type.
* In the second day she collects 8 pebbles of the fourth type.
* In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.
* In the fourth day she collects 7 pebbles of the fifth type.
* In the fifth day she collects 1 pebble of the second type. | instruction | 0 | 60,287 | 14 | 120,574 |
Tags: implementation, math
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 14:40:49 2019
@author: avina
"""
from math import ceil
n,m = map(int, input().split())
l = list(map(int, input().split()))
i = 0;u = 0
days = 0
while i <n:
if l[i] >= 2*m:
days+= l[i]//(2*m)
b = l[i]%(2*m)
if b >m:
days+=1
else:
if b!= 0:
u+=1
elif l[i]>m:
days+=1
else:
u+=1
i+=1
print(days+ceil(u/2))
``` | output | 1 | 60,287 | 14 | 120,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.
Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
Input
The first line contains two integers n and k (1 β€ n β€ 105, 1 β€ k β€ 109) β the number of different pebble types and number of pebbles Anastasia can place in one pocket.
The second line contains n integers w1, w2, ..., wn (1 β€ wi β€ 104) β number of pebbles of each type.
Output
The only line of output contains one integer β the minimum number of days Anastasia needs to collect all the pebbles.
Examples
Input
3 2
2 3 4
Output
3
Input
5 4
3 1 8 9 7
Output
5
Note
In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type β on the second day, and of third type β on the third day.
Optimal sequence of actions in the second sample case:
* In the first day Anastasia collects 8 pebbles of the third type.
* In the second day she collects 8 pebbles of the fourth type.
* In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.
* In the fourth day she collects 7 pebbles of the fifth type.
* In the fifth day she collects 1 pebble of the second type. | instruction | 0 | 60,288 | 14 | 120,576 |
Tags: implementation, math
Correct Solution:
```
def solve():
n, k = map(int, input().split())
w = [int(i) for i in input().split()]
ans = sum((wi + k - 1) // k for wi in w)
ans = (ans + 1) // 2
print(ans)
if __name__ == '__main__':
solve()
``` | output | 1 | 60,288 | 14 | 120,577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.