message stringlengths 2 433k | message_type stringclasses 2
values | message_id int64 0 1 | conversation_id int64 113 108k | cluster float64 12 12 | __index_level_0__ int64 226 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!
An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 β€ x,y,z β€ n), a_{x}+a_{y} β a_{z} (not necessarily distinct).
You are given one integer n. Please find any complete array of length n. It is guaranteed that under given constraints such array exists.
Input
Each test contains multiple test cases. The first line contains t (1 β€ t β€ 1000) β the number of test cases. Description of the test cases follows.
The only line of each test case contains one integer n (1 β€ n β€ 1000).
It is guaranteed that the sum of n over all test cases does not exceed 1000.
Output
For each test case, print a complete array on a single line. All elements have to be integers between 1 and 1000 and for all indices x,y,z (1 β€ x,y,z β€ n) (not necessarily distinct), a_{x}+a_{y} β a_{z} must hold.
If multiple solutions exist, you may print any.
Example
Input
2
5
4
Output
1 5 3 77 12
384 384 44 44
Note
It can be shown that the outputs above are valid for each test case. For example, 44+44 β 384.
Below are some examples of arrays that are NOT complete for the 1st test case:
[1,2,3,4,5]
Notice that a_{1}+a_{2} = a_{3}.
[1,3000,1,300,1]
Notice that a_{2} = 3000 > 1000. | instruction | 0 | 31,907 | 12 | 63,814 |
Tags: constructive algorithms, implementation
Correct Solution:
```
t=int(input())
for i in range(t):
n=int(input())
arr=[1]*n
print(*arr)
``` | output | 1 | 31,907 | 12 | 63,815 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable. | instruction | 0 | 32,080 | 12 | 64,160 |
Tags: implementation
Correct Solution:
```
def main():
n = int(input())
a = [int(x) for x in input().split()]
temp = [1] * n
for i in range(1, n):
if a[i] != a[i-1]:
temp[i] = temp[i-1]+1
else:
temp[i] = 1
print((max(temp) - 1)//2)
temp2 = [-1] * n
i = 0
while i < n:
if a[i] == 0:
j = i
while j+2 < n and a[j+1] == 1 and a[j+2] == 0:
j += 2
if j == n-1 or a[j+1] == 0:
while i <= j:
temp2[i] = 0
i += 1
else:
l = j - i + 1
m = i + l//2
while i <= m:
temp2[i] = 0
i += 1
while i <= j:
temp2[i] = 1
i += 1
else:
j = i
while j+2 < n and a[j+1] == 0 and a[j+2] == 1:
j += 2
if j == n-1 or a[j+1] == 1:
while i <= j:
temp2[i] = 1
i += 1
else:
l = j - i + 1
m = i + l//2
while i <= m:
temp2[i] = 1
i += 1
while i <= j:
temp2[i] = 0
i += 1
print(*temp2)
#------------------ Python 2 and 3 footer by Pajenegod and c1729-----------------------------------------
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
main()
``` | output | 1 | 32,080 | 12 | 64,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable. | instruction | 0 | 32,081 | 12 | 64,162 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
cnt = 0
cur = a[0]
ind = []
i = 0
ind.append((0, 0))
while i < len(a):
left = i
right = i
while i + 1 < len(a) and cur != a[i + 1]:
cur = a[i + 1]
i += 1
right += 1
ind.append((left, right))
i += 1
maxn = 0
ind.append((len(a) - 1, len(a) - 1))
for i in range(len(ind)):
if (ind[i][1] - ind[i][0])//2 > maxn:
maxn = (ind[i][1] - ind[i][0])//2
print(maxn)
for i in range(1, len(ind) - 1):
if a[ind[i - 1][1]] == a[ind[i + 1][0]]:
for j in range(ind[i][0], ind[i][1] + 1):
print(a[ind[i - 1][1]], end = ' ')
else:
for j in range(ind[i][0], (ind[i][0] + ind[i][1] + 1) // 2):
print(a[ind[i - 1][1]], end = ' ')
for j in range((ind[i][0] + ind[i][1] + 1) // 2, ind[i][1] + 1):
print(a[ind[i + 1][0]], end = ' ')
``` | output | 1 | 32,081 | 12 | 64,163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable. | instruction | 0 | 32,082 | 12 | 64,164 |
Tags: implementation
Correct Solution:
```
def main():
n, l = int(input()), input().split()
x, a = [False] * n, l[0]
for i, b in enumerate(l):
if a == b:
x[i] = x[i - 1] = True
a = b
b = 0
for i, a in enumerate(x):
if a:
if b:
if b & 1:
a = l[i]
for j in range(i - b, i):
l[j] = a
else:
a = l[i - 1]
for j in range(i - b, i - b // 2 + 1):
l[j] = a
a = l[i]
for j in range(j, i):
l[j] = a
b = 0
else:
b += 1
x[i] = b
print((max(x) + 1) // 2)
print(' '.join(l))
if __name__ == '__main__':
main()
``` | output | 1 | 32,082 | 12 | 64,165 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable. | instruction | 0 | 32,083 | 12 | 64,166 |
Tags: implementation
Correct Solution:
```
import math as mt
import sys,string,bisect
input=sys.stdin.readline
import random
from collections import deque,defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
d=defaultdict(list)
n=I()
a=L()
def solve(l,r):
if(l==r):
return 0
if(a[l]==a[r]):
for i in range(l+1,r):
a[i]=a[l]
return (r-l)//2
else:
m=(l+r+1)//2
for i in range(l+1,m):
a[i]=a[l]
for i in range(m,r):
a[i]=a[r]
return (r-l-1)//2
left=0
ans=0
for i in range(n):
if(i==n-1 or a[i]==a[i+1]):
ans=max(ans,solve(left,i))
left=i+1
print(ans)
print(*a)
``` | output | 1 | 32,083 | 12 | 64,167 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable. | instruction | 0 | 32,084 | 12 | 64,168 |
Tags: implementation
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
MOD=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n=Int()
a=array()
steps=0
ans=set()
l=1
r=0
for i in range(1,n-1):
if(a[i-1]==a[i+1] and a[i-1]!=a[i]):
steps+=1
r+=1
else:
if(l<=r): ans.add((l,r))
l=i+1
r=i
steps=0
if(l<=r): ans.add((l,r))
steps=0
b=a
for l,r in ans:
tot=r-l+1
steps=max(tot,steps)
if(tot%2):
b[l:r+1]=[a[l-1]]*(tot)
else:
b[l:l+tot//2]=[a[l-1]]*(tot//2)
b[l+tot//2:r+1]=[a[r+1]]*(tot//2)
print(ceil(steps/2))
print(*b)
``` | output | 1 | 32,084 | 12 | 64,169 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable. | instruction | 0 | 32,085 | 12 | 64,170 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
r, b, c = 0, [a[0]], 0
for x, y, z in zip(a, a[1:], a[2:]):
if x != y != z:
c += 1
else:
if c & 1:
b.extend([y]*(c+1))
else:
b.extend([1-y]*(c//2) + [y]*(c//2+1))
r = max(r, (c+1)//2)
c = 0
y = a[-1]
if c & 1:
b.extend([y]*(c+1))
else:
b.extend([1-y]*(c//2) + [y]*(c//2+1))
r = max(r, (c+1)//2)
print(r)
print(*b)
``` | output | 1 | 32,085 | 12 | 64,171 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable. | instruction | 0 | 32,086 | 12 | 64,172 |
Tags: implementation
Correct Solution:
```
N = int(input())
seq = [ i for i in input().split() ]
def end_lst(i):
while i < N - 1 and seq[i] != seq[i + 1]:
i = i + 1
return i
def reorder(lst, start, end):
if start == end - 1:
return 0
if lst[start] == lst[end]:
for i in range(start, end + 1):
lst[i] = lst[start]
return (end - start) // 2
mid = (start + end) // 2
for i in range(start, mid + 1):
lst[i] = lst[start]
for i in range(mid + 1, end + 1):
lst[i] = lst[end]
return (end - start + 1) // 2 - 1
i, ans = 0, 0
while i < N - 1:
if seq[i] != seq[i + 1]:
end = end_lst(i)
ans = max(reorder(seq, i, end), ans)
i = end
else:
i += 1
print(ans)
print(" ".join(seq))
``` | output | 1 | 32,086 | 12 | 64,173 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable. | instruction | 0 | 32,087 | 12 | 64,174 |
Tags: implementation
Correct Solution:
```
def main():
n = int(input())
a = [int(i) for i in input().split()]
flag = 0
now_begin = 0
kek = 0
ans = [[-1] * 2 for i in range(n)]
for i in range(1, n - 1):
if a[i] != a[i - 1] and a[i] != a[i + 1]:
kek += 1
else:
flag = max((kek + 1) // 2, flag)
now_end = i
if a[now_begin] == a[now_end]:
ans[now_begin + 1][0] = a[now_begin]
ans[now_begin + 1][1] = kek
else:
ans[now_begin + 1][0] = a[now_begin]
ans[now_begin + 1][1] = kek // 2
ans[now_begin + 1 + kek // 2][0] = a[now_end]
ans[now_begin + 1 + kek // 2][1] = kek // 2
now_begin = now_end
kek = 0
flag = max((kek + 1) // 2, flag)
print(flag)
now_end = n - 1
if a[now_begin] == a[now_end]:
ans[now_begin + 1][0] = a[now_begin]
ans[now_begin + 1][1] = kek
else:
ans[now_begin + 1][0] = a[now_begin]
ans[now_begin + 1][1] = kek // 2
ans[now_begin + 1 + kek // 2][0] = a[now_end]
ans[now_begin + 1 + kek // 2][1] = kek // 2
g = 0
what = 0
for i in range(n):
if ans[i].count(-1) != 2:
what = ans[i][0]
g = ans[i][1]
if g <= 0:
what = a[i]
a[i] = what
g -= 1
for i in range(n):
a[i] = str(a[i])
print(' '.join(a))
main()
``` | output | 1 | 32,087 | 12 | 64,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Submitted Solution:
```
from math import ceil
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
narr = [True]
for i in range(1, n - 1):
x = arr[i]
narr.append(x == arr[i - 1] or x == arr[i + 1])
narr.append(True)
cnt = 0
mc = 0
for x in narr:
if not x:
cnt += 1
if x and cnt:
mc = max(mc, cnt)
cnt = 0
if cnt:
mc = max(mc, cnt)
print(ceil(mc / 2))
ss = None
for i, x in enumerate(arr):
if not narr[i]:
if ss is None:
ss = i
elif ss is not None:
if arr[ss - 1] == x:
for j in range(ss, i):
arr[j] = x
else:
for j in range(ss, i):
arr[j] = arr[ss - 1] if j < (i + ss) / 2 else x
ss = None
print(*arr)
``` | instruction | 0 | 32,088 | 12 | 64,176 |
Yes | output | 1 | 32,088 | 12 | 64,177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Submitted Solution:
```
import math
n=int(input())
a=list(map(int,input().split()))
segs=[]
st=-1
for i in range(n):
iso=False if i==0 or i==n-1 else a[i-1]==a[i+1] and a[i]!=a[i-1]
if iso and st==-1:
st=i
elif not iso and st!=-1:
segs.append((st,i-1))
st=-1
ans=0
for l,r in segs:
span=r-l+1
ans=max(ans,span)
for i in range(span//2):
a[l+i]=a[l-1]
a[r-i]=a[r+1]
if span%2:
j=l+span//2
a[j]=sorted([a[j-1],a[j],a[j+1]])[1]
print(math.ceil(ans/2))
print(*a)
``` | instruction | 0 | 32,089 | 12 | 64,178 |
Yes | output | 1 | 32,089 | 12 | 64,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left)/ 2)
# Check if middle element is
# less than or equal to key
if (arr[mid]<=key):
count = mid+1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater( arr,n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n=int(input())
l=list(map(int,input().split()))
ans=0
cur=0
st=-1
for i in range(1,n-1):
if l[i]!=l[i-1]:
if st==-1:
st=i
#cur+=1
else:
if st==-1:
continue
for j in range(st,i-1):
if j>(i-2-j+st):
break
rt=l[j]
l[j]=l[j-1]
l[i-2-(j-st)]=l[i-1-j+st]
cur+=1
ans=max(ans,cur)
cur=0
st=-1
if st!=-1:
i=n-1
if l[-1]!=l[-2]:
i+=1
for j in range(st, i - 1):
if j > (i - 2 - j + st):
break
rt=l[j]
l[j] = l[j - 1]
l[i - 2 - (j - st)] = l[i - 1 - j + st]
cur+=1
ans=max(ans,cur)
print(ans)
print(*l)
``` | instruction | 0 | 32,090 | 12 | 64,180 |
Yes | output | 1 | 32,090 | 12 | 64,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
steps = 0
i = 0
b = [None]*n
while i < n-1:
j = i
while j < n-1 and a[j] != a[j+1]: j += 1
span = j - i + 1
half_span = span//2
for k in range(i,i+half_span):
b[k] = a[i]
for k in range(i+half_span, i+span):
b[k] = a[j]
steps = max(steps, (span-1)//2)
i = j+1
if (i == n-1):
b[i] = a[i]
print(steps)
print(" ".join(map(str,b)))
``` | instruction | 0 | 32,091 | 12 | 64,182 |
Yes | output | 1 | 32,091 | 12 | 64,183 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Submitted Solution:
```
import sys
from sys import stdin, stdout
n = int(input())
nlist = [int(x) for x in stdin.readline().rstrip().split()]
def transform(nlist):
res = []
sum = nlist[0]+nlist[1]+nlist[2]
for i in range(len(nlist)):
if i == 0:
#stdout.write(str(nlist[i])+" ")
res.append(nlist[i])
elif i == (len(nlist)-1):
#stdout.write(str(nlist[i])+"\n")
res.append(nlist[i])
else:
if sum <= 1:
#stdout.write("0 ")
res.append(0)
else:
#stdout.write("1 ")
res.append(1)
sum -= nlist[i-1]
sum += nlist[i+1]
return res
def isdiff(list1,list2):
isdiff = False
for i in range(len(list1)):
if not list1[i] == list2[i]:
isdiff = True
break
return isdiff
start_list = nlist
count = 0
transformed = transform(nlist)
if not isdiff(transformed,nlist):
print("0")
for i in range(len(transformed)):
if i < len(transformed) - 1:
stdout.write(str(transformed[i])+" ")
else:
stdout.write(str(transformed[i]))
else:
count = 1
while isdiff(transformed,nlist):
nlist = transformed
transformed = transform(transformed)
count += 1
print(count)
for i in range(len(transformed)):
if i < len(transformed) - 1:
stdout.write(str(transformed[i])+" ")
else:
stdout.write(str(transformed[i]))
``` | instruction | 0 | 32,092 | 12 | 64,184 |
No | output | 1 | 32,092 | 12 | 64,185 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Submitted Solution:
```
n=int(input())
b=[int(t) for t in input().strip().split()]
a=b+[b[-1]]
current=1
is_alternating=False
break_points=[]
for current in range(1,len(a)):
if(a[current]!=a[current-1] and is_alternating==False):
break_points.append(current-1)
is_alternating=True
elif(a[current]==a[current-1] and is_alternating==True):
break_points.append(current-1)
is_alternating=False
k=-1
for i in range(len(break_points)-1):
p=break_points[i]
q=break_points[i+1]
if(a[p]==a[q]):
k=max([k,(q-p+1-1)//2])
for j in range(p,q):
a[j]=a[p]
elif(a[p]!=a[q]):
k=max([k,(q-p+1-2)//2])
for j in range(p,p+(q-p)//2):
a[j]=a[p]
for j in range(p+(q-p)//2+1,q):
a[j]=a[q]
print(k)
print(' '.join([str(t) for t in a[:-1]]))
``` | instruction | 0 | 32,093 | 12 | 64,186 |
No | output | 1 | 32,093 | 12 | 64,187 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Submitted Solution:
```
from math import sqrt, pow, log, log2, log10, exp
from copy import deepcopy
from fractions import gcd
def read_ints():
return list(map(int, input().split()))
def read_int():
return read_ints()[0]
def read_floats():
return list(map(float, input().split()))
def read_float():
return read_floats()[0]
def format_list(l):
return ' '.join(list(map(str, l)))
def one_dim_array(n, value=0):
return [deepcopy(value) for x in range(n)]
def two_dim_array(n, m, value=0):
return [[deepcopy(value) for x in range(m)] for x in range(n)]
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, sqrt(n) + 1):
if n % i == 0:
return False
return True
def max_len_sublist(l, f):
start, max_length, length = 0, 0, 0
for i in range(1, len(l)):
if f(l[i], l[i - 1]):
length += 1
else:
if max_length < length:
start = i - length
max_length = length
length = 0
return start, max_length
def tf_to_yn(b):
return 'YES' if b else 'NO'
def longest_non_descent_subsequence(s, restore_sequence=False):
d = one_dim_array(len(s), 0)
for i in range(len(s)):
possible = [d[j] + 1 if s[j] <= s[i] else 1 for j in range(i)]
d[i] = 1 if len(possible) == 0 else max(possible)
if not restore_sequence:
return d[-1] if len(d) != 0 else 0
def count(p, l):
count = 0
for i in range(len(l)):
if p(l[i]):
count += 1
return count
n = read_int()
a = read_ints()
start = 0
i = 1
r = [0]
zero_count = 1 if a[0] == 0 else 0
while i < len(a):
if a[i] != a[i - 1]:
if a[i] == 0:
zero_count += 1
i += 1
if i != len(a):
continue
j = start + 1
length = i - start
if zero_count == length / 2:
dom = a[start]
ndom = 0 if dom == 1 else 1
j = start + 1
while j < start + zero_count:
a[j] = dom
j += 1
while j < i - 1:
a[j] = ndom
j += 1
if length > 2:
r.append(1)
start = i
i += 1
continue
dom = 0 if zero_count > length / 2 else 1
while j < i - 1:
a[j] = dom
j += 1
if length > 2:
r.append(2)
start = i
i += 1
zero_count=0
print(max(r))
print(' '.join(list(map(str, a))))
``` | instruction | 0 | 32,094 | 12 | 64,188 |
No | output | 1 | 32,094 | 12 | 64,189 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 β€ n β€ 500 000) β the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer β the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space β the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Submitted Solution:
```
def solve():
N = int(input())
A = list(map(int, input().split()))
A.append(A[-1])
ma = 0
s = p = 0
for i in range(1, len(A)):
if A[i] != A[p]:
p = i
continue
else:
e = p
if A[s] == A[e]:
ma = max(ma, 1)
for j in range(s, e):
A[j] = A[s]
else:
l = (p - s + 1) // 2
for j in range(1, l):
A[s + j] = A[s]
A[e - j] = A[e]
ma = max(ma, (p - s) // 2)
s = i
A.pop()
print(ma)
print(' '.join(map(str, A)))
if __name__ == '__main__':
solve()
``` | instruction | 0 | 32,095 | 12 | 64,190 |
No | output | 1 | 32,095 | 12 | 64,191 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Blake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special.
You are given an array a of length n. The characteristic of this array is the value <image> β the sum of the products of the values ai by i. One may perform the following operation exactly once: pick some element of the array and move to any position. In particular, it's allowed to move the element to the beginning or to the end of the array. Also, it's allowed to put it back to the initial position. The goal is to get the array with the maximum possible value of characteristic.
<image>
Input
The first line of the input contains a single integer n (2 β€ n β€ 200 000) β the size of the array a.
The second line contains n integers ai (1 β€ i β€ n, |ai| β€ 1 000 000) β the elements of the array a.
Output
Print a single integer β the maximum possible value of characteristic of a that can be obtained by performing no more than one move.
Examples
Input
4
4 3 2 5
Output
39
Input
5
1 1 2 7 1
Output
49
Input
3
1 1 2
Output
9
Note
In the first sample, one may pick the first element and place it before the third (before 5). Thus, the answer will be 3Β·1 + 2Β·2 + 4Β·3 + 5Β·4 = 39.
In the second sample, one may pick the fifth element of the array and place it before the third. The answer will be 1Β·1 + 1Β·2 + 1Β·3 + 2Β·4 + 7Β·5 = 49.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=sorted(a)
ans1=ans2=0
po=0
ki=n-1
for i in range(n):
if a[i]!=b[i]: po=i; break
for i in range(n-1,-1,-1):
if a[i]!=b[i]: ki=i; break
pmi=po
pma=po
for i in range(po,ki+1):
if a[pmi]>=a[i]: pmi=i
for i in range(po,ki+1):
if a[pma]<a[i]: pma=i
b=a[:]
t=a.pop(pmi); a=a[:po]+[t]+a[po:]
t=b.pop(pma); b=b[:ki-1]+[t]+b[ki-1:]
sa=sb=0
for i in range(n): sa+=i*a[i]+a[i]; sb+=i*b[i]+b[i]
print(sa if sa>sb else sb)
``` | instruction | 0 | 32,096 | 12 | 64,192 |
No | output | 1 | 32,096 | 12 | 64,193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Blake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special.
You are given an array a of length n. The characteristic of this array is the value <image> β the sum of the products of the values ai by i. One may perform the following operation exactly once: pick some element of the array and move to any position. In particular, it's allowed to move the element to the beginning or to the end of the array. Also, it's allowed to put it back to the initial position. The goal is to get the array with the maximum possible value of characteristic.
<image>
Input
The first line of the input contains a single integer n (2 β€ n β€ 200 000) β the size of the array a.
The second line contains n integers ai (1 β€ i β€ n, |ai| β€ 1 000 000) β the elements of the array a.
Output
Print a single integer β the maximum possible value of characteristic of a that can be obtained by performing no more than one move.
Examples
Input
4
4 3 2 5
Output
39
Input
5
1 1 2 7 1
Output
49
Input
3
1 1 2
Output
9
Note
In the first sample, one may pick the first element and place it before the third (before 5). Thus, the answer will be 3Β·1 + 2Β·2 + 4Β·3 + 5Β·4 = 39.
In the second sample, one may pick the fifth element of the array and place it before the third. The answer will be 1Β·1 + 1Β·2 + 1Β·3 + 2Β·4 + 7Β·5 = 49.
Submitted Solution:
```
import bisect
import operator
class Point(tuple):
def __new__(self, a, b):
return tuple.__new__(self, (a, b))
def __add__(self, x):
if type(x) != type(self): x = Point(x, 1)
return Point(self[0] * x[1] + self[1] * x[0], self[1] * x[1])
def __sub__(self, x):
if type(x) != type(self): x = Point(x, 1)
return Point(self[0] * x[1] - self[1] * x[0], self[1] * x[1])
def __neg__(self):
return Point(-self[0], self[1])
def __mul__(self, x):
if type(x) != type(self): x = Point(x, 1)
return Point(x[0] * self[0], x[1] * self[1])
def __rmul__(self, k):
return self.__mul__(k)
def __eq__(self, x):
if type(x) != type(self): x = Point(x, 1)
return self[0] * x[1] == self[1] * x[0]
def __le__(self, x):
if type(x) != type(self): x = Point(x, 1)
return self[0] * x[1] <= self[1] * x[0]
def __ge__(self, x):
if type(x) != type(self): x = Point(x, 1)
return self[0] * x[1] >= self[1] * x[0]
def __ne__(self, x): return not self.__eq__(x)
def __gt__(self, x): return not self.__le__(x)
def __lt__(self, x): return not self.__ge__(x)
class LinearFunction(tuple):
def __new__(self, a, b):
return tuple.__new__(self, (a, b))
def __add__(self, f):
return LinearFunction(self[0] + f[0], self[1] + f[1])
def __sub__(self, f):
return LinearFunction(self[0] - f[0], self[1] - f[1])
def __neg__(self):
return LinearFunction(-self[0], -self[1])
def __mul__(self, k):
return LinearFunction(k * self[0], k * self[1])
def __rmul__(self, k):
return self.__mul__(k)
def __call__(self, x):
return self[0] * x + self[1]
def __and__(self, f):
return Point(self[1] -f[1], f[0] - self[0])
class ConvexHull():
def __init__(self, L):
self.stack, self.points = [], []
for f in sorted(L):
while len(self.stack) > 1 and f(self.points[-1]) >= self.stack[-1](self.points[-1]):
self.stack.pop()
self.points.pop()
if self.stack:
x = self.stack[-1] & f
self.stack.append(f)
self.points.append(x)
else:
self.stack.append(f)
def __call__(self, x):
i = bisect.bisect(self.points, x)
return self.stack[i](x)
from itertools import accumulate
def solve():
n = int(input())
A = [0] + [int(x) for x in input().split()]
S = list(accumulate(A))
C = ConvexHull(LinearFunction(l, -S[l]) for l in range(n+1))
return max(C(A[r]) + S[r] - r*A[r] for r in range(n+1)) + sum(r*A[r] for r in range(n+1))
print(solve())
``` | instruction | 0 | 32,097 | 12 | 64,194 |
No | output | 1 | 32,097 | 12 | 64,195 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Blake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special.
You are given an array a of length n. The characteristic of this array is the value <image> β the sum of the products of the values ai by i. One may perform the following operation exactly once: pick some element of the array and move to any position. In particular, it's allowed to move the element to the beginning or to the end of the array. Also, it's allowed to put it back to the initial position. The goal is to get the array with the maximum possible value of characteristic.
<image>
Input
The first line of the input contains a single integer n (2 β€ n β€ 200 000) β the size of the array a.
The second line contains n integers ai (1 β€ i β€ n, |ai| β€ 1 000 000) β the elements of the array a.
Output
Print a single integer β the maximum possible value of characteristic of a that can be obtained by performing no more than one move.
Examples
Input
4
4 3 2 5
Output
39
Input
5
1 1 2 7 1
Output
49
Input
3
1 1 2
Output
9
Note
In the first sample, one may pick the first element and place it before the third (before 5). Thus, the answer will be 3Β·1 + 2Β·2 + 4Β·3 + 5Β·4 = 39.
In the second sample, one may pick the fifth element of the array and place it before the third. The answer will be 1Β·1 + 1Β·2 + 1Β·3 + 2Β·4 + 7Β·5 = 49.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=sorted(a)
ans1=ans2=0
po=0
ki=n-1
for i in range(n):
if a[i]!=b[i]: po=i; break
for i in range(n-1,-1,-1):
if a[i]!=b[i]: ki=i; break
pmi=po
pma=po
for i in range(po,ki+1):
if a[pmi]>=a[i]: pmi=i
for i in range(po,ki+1):
if a[pma]<a[i]: pma=i
b=a[:]
if po==0: t=a.pop(pmi); a=[t]+a
else: t=a.pop(pmi); a=a[:po]+[t]+a[po:]
if ki==n-1: t=b.pop(pma); b+=[t]
else: t=b.pop(pma); b=b[:ki+1]+[t]+b[ki+1:]
sa=sb=0
for i in range(n): sa+=i*a[i]+a[i]; sb+=i*b[i]+b[i]
print(sa if sa>sb else sb)
``` | instruction | 0 | 32,098 | 12 | 64,196 |
No | output | 1 | 32,098 | 12 | 64,197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Blake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special.
You are given an array a of length n. The characteristic of this array is the value <image> β the sum of the products of the values ai by i. One may perform the following operation exactly once: pick some element of the array and move to any position. In particular, it's allowed to move the element to the beginning or to the end of the array. Also, it's allowed to put it back to the initial position. The goal is to get the array with the maximum possible value of characteristic.
<image>
Input
The first line of the input contains a single integer n (2 β€ n β€ 200 000) β the size of the array a.
The second line contains n integers ai (1 β€ i β€ n, |ai| β€ 1 000 000) β the elements of the array a.
Output
Print a single integer β the maximum possible value of characteristic of a that can be obtained by performing no more than one move.
Examples
Input
4
4 3 2 5
Output
39
Input
5
1 1 2 7 1
Output
49
Input
3
1 1 2
Output
9
Note
In the first sample, one may pick the first element and place it before the third (before 5). Thus, the answer will be 3Β·1 + 2Β·2 + 4Β·3 + 5Β·4 = 39.
In the second sample, one may pick the fifth element of the array and place it before the third. The answer will be 1Β·1 + 1Β·2 + 1Β·3 + 2Β·4 + 7Β·5 = 49.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=sorted(a)
ans1=ans2=0
po=0
ki=n-1
for i in range(n):
if a[i]!=b[i]: po=i; break
for i in range(n-1,-1,-1):
if a[i]!=b[i]: ki=i; break
pmi=po
pma=po
for i in range(po,ki+1):
if a[pmi]>=a[i]: pmi=i
for i in range(po,ki+1):
if a[pma]<a[i]: pma=i
b=a[:]
c=a[:]
if po==0: t=a.pop(pmi); a=[t]+a
else: t=a.pop(pmi); a=a[:po]+[t]+a[po:]
if ki==n-1: t=b.pop(pma); b+=[t]
else: t=b.pop(pma); b=b[:ki]+[t]+b[ki:]
sa=sb=0
for i in range(n): sa+=i*a[i]+a[i]; sb+=i*b[i]+b[i]
print(sa if sa>sb else sb)
``` | instruction | 0 | 32,099 | 12 | 64,198 |
No | output | 1 | 32,099 | 12 | 64,199 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1 | instruction | 0 | 32,100 | 12 | 64,200 |
Tags: binary search, dp, two pointers
Correct Solution:
```
L=list(map(int,input().split()))
n=L[0]
k=L[1]
a=list(map(int,input().split()))
nbr0=0
posi=0
taillemax=0
p=0
for i in range(len(a)):
nbr0+=(a[i]==0)
if nbr0>k:
if (i-posi)>taillemax:
p=posi
taillemax=i-posi
j=posi
while 1:
if a[j]==0:
posi=j+1
break
j=j+1
nbr0-=1
if i==(n-1) and (i-posi+1)>taillemax:
p=posi
taillemax=i-posi+1
#print(p,posi)
print(taillemax)
ch=""
for i in range(len(a)):
if i>=p and i<(p+taillemax):
ch+="1 "
else:
ch+=str(a[i])+" "
print(ch)
``` | output | 1 | 32,100 | 12 | 64,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1 | instruction | 0 | 32,101 | 12 | 64,202 |
Tags: binary search, dp, two pointers
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
l, r = 0, 0
ans_idx, ans_len = 0, 0
zeros = 0
while r < n:
# slide window
if r < n:
zeros += a[r] == 0
r += 1
if zeros > k:
zeros -= a[l] == 0
l += 1
if r - l > ans_len:
ans_len = r - l
ans_idx = l
print(ans_len)
zeros = 0
for i in range(n):
if i < ans_idx:
print(a[i], end=' ')
elif i >= ans_idx and zeros < k:
zeros += a[i] == 0
print(1, end=' ')
else:
print(a[i], end=' ')
``` | output | 1 | 32,101 | 12 | 64,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1 | instruction | 0 | 32,102 | 12 | 64,204 |
Tags: binary search, dp, two pointers
Correct Solution:
```
ch=input()
ch1=input()
ch=ch.split(' ')
n=int(ch[0])
k=int(ch[1])
l=ch1.split(' ')
l=[int(i) for i in l]
nb=l.count(0)
if k>=nb:
print(n)
l=['1']*n
ch2=' '.join(l)
print(ch2)
else:
c=0
t=[]
while (len(t)<nb):
if (l[c]==0):
t.append(c)
c=c+1
m=0
j=0
while (j+k+1<nb):
d= t[j+k+1]-t[j]-1
j=j+1
if (m<d) :
m=d
c=j
if m<t[k]:
m=t[k]
c=0
if m<n-1-t[nb-k-1]:
m=n-1-t[nb-k-1]
c=nb-k
for i in range(c,c+k):
l[t[i]]=1
l=[str(i) for i in l]
ch2=' '.join(l)
print(m)
print(ch2)
``` | output | 1 | 32,102 | 12 | 64,205 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1 | instruction | 0 | 32,103 | 12 | 64,206 |
Tags: binary search, dp, two pointers
Correct Solution:
```
n,k=map(int,input().split())
l=list(map(int,input().split()))
m=0
z=0
p=0
r=0
for i in range(n):
if l[i]==0:
z+=1
if z<=k:
m+=1
r=i
else:
if l[p]==0 :
z-= 1
p+=1
print(m)
l[r-m+1:r+1]=[1]*m
print(*l)
``` | output | 1 | 32,103 | 12 | 64,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1 | instruction | 0 | 32,104 | 12 | 64,208 |
Tags: binary search, dp, two pointers
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
from collections import Counter
# c=sorted((i,int(val))for i,val in enumerate(input().split()))
import heapq
# c=sorted((i,int(val))for i,val in enumerate(input().split()))
# n = int(input())
# ls = list(map(int, input().split()))
# n, k = map(int, input().split())
# n =int(input())
#arr=[(i,x) for i,x in enum]
#arr.sort(key=lambda x:x[0])
#print(arr)
import math
# e=list(map(int, input().split()))
from collections import Counter
#print("\n".join(ls))
#print(os.path.commonprefix(ls[0:2]))
#n=int(input())
from bisect import bisect_right
#for _ in range(int(input())):
#for _ in range(int(input())):
n,k=map(int, input().split())
arr=list(map(int, input().split()))
cnt1=0
j=0
ans=0
ind=[-1,-1]
for i in range(n):
if arr[i]==0:
cnt1+=1
if cnt1<=k:
if i-j+1>ans:
ind=[j,i]
ans=max(ans,i-j+1)
else:
while cnt1>k and j<=i:
if arr[j]==0:
cnt1-=1
j+=1
print(ans)
for i in range(n):
if i>=ind[0] and i<=ind[1]:
print(1,end=" ")
else:
print(arr[i],end=" ")
``` | output | 1 | 32,104 | 12 | 64,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1 | instruction | 0 | 32,105 | 12 | 64,210 |
Tags: binary search, dp, two pointers
Correct Solution:
```
s=list(map(int,input().split()))
s1=list(map(int,input().split()))
start=0
end=0
c=0
s2=0
x=0
y=0
while(end<s[0]):
if(s1[end]==0):
c+=1
while(c>s[1]):
c+=s1[start]-1
start+=1
if(end-start+1>s2):
s2=end-start+1
x=start
y=end
end+=1
print(s2)
for i in range(x,y+1):
if(s2>0):
if(s1[i]==0):
s1[i]=1
s2-=1
print(*s1)
``` | output | 1 | 32,105 | 12 | 64,211 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1 | instruction | 0 | 32,106 | 12 | 64,212 |
Tags: binary search, dp, two pointers
Correct Solution:
```
n, k = map(int, input().split())
s = list(map(int, input().split()))
ans = 0
def get(x) :
return 1 - x
l = 0
cnt = 0
L = n
R = 0
for i in range(n) :
cnt += get(s[i])
while cnt > k :
cnt -= get(s[l])
l += 1
if l <= i :
now = i - l + 1
if now > ans :
ans = now
L = l
R = i
if L <= R :
for i in range(L, R + 1) :
s[i] = 1
print(ans)
print(' '.join(map(str,s)))
``` | output | 1 | 32,106 | 12 | 64,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1 | instruction | 0 | 32,107 | 12 | 64,214 |
Tags: binary search, dp, two pointers
Correct Solution:
```
n,k=map(int,input().split())
a=[int(x) for x in input().split()]
i=0
j=0
c=0
an=0
p=[0,n-1]
while (j<n and c<k):
if a[j]==0 :
c+=1
j+=1
an=j-i
p=[i,j]
while (j<n):
if a[j]==0:
while (a[i]!=0):
i+=1
i+=1
j+=1
if (j-i)>an:
an=j-i
p=[i,j]
print(an)
print(*(a[:p[0]]+['1']*an + a[p[1]:]))
``` | output | 1 | 32,107 | 12 | 64,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
Submitted Solution:
```
def read_ints():
return [int(x)for x in input().split()]
def main():
n,k = read_ints();
a = read_ints()
lo = 0
hi = 0
count = 0
x = -1
y = -1
while hi<n:
if count < k or a[hi]!=0:
if a[hi] == 0:
count += 1
if hi - lo >= y - x:
x = lo
y = hi
hi+=1
else:
if a[lo] == 0:
count -= 1
lo += 1
if x!=-1:
print(y-x+1)
for i in range(x,y+1):
a[i] = 1
print(" ".join(map(str,a)))
else:
print(0)
print(" ".join(map(str,a)))
main()
``` | instruction | 0 | 32,108 | 12 | 64,216 |
Yes | output | 1 | 32,108 | 12 | 64,217 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
Submitted Solution:
```
import sys
import inspect
import re
import math
from pprint import pprint as pp
mod = 998244353
MAX = 10**15
def deb(p):
for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bdeb\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
print('%s %d' % (m.group(1), p))
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
m, z, v, e = 0, 0, 0, 0
for i in range(n):
if a[i] == 0:
z += 1
if z <= k:
m += 1
e = i
else:
if a[v] == 0:
z -= 1
v += 1
print(m)
for i in range(e - m + 1, e + 1):
a[i] = 1
print(' '.join(map(str, a)))
if __name__ == '__main__':
main()
``` | instruction | 0 | 32,109 | 12 | 64,218 |
Yes | output | 1 | 32,109 | 12 | 64,219 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
Submitted Solution:
```
def read_ints():
return [int(x) for x in input().split()]
def main():
n, k = read_ints()
a = read_ints()
lo = 0
hi = 0
count = 0
x = -1
y = -1
while hi < n:
if count < k or a[hi] != 0:
if a[hi] == 0:
count += 1
if hi - lo >= y - x:
x = lo
y = hi
hi += 1
else:
if a[lo] == 0:
count -= 1
lo += 1
if x != -1:
print(y - x + 1)
for i in range(x, y + 1):
a[i] = 1
print(" ".join(map(str, a)))
else:
print(0)
print(" ".join(map(str, a)))
main()
``` | instruction | 0 | 32,110 | 12 | 64,220 |
Yes | output | 1 | 32,110 | 12 | 64,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
Submitted Solution:
```
from sys import stdin, stdout
L=list(map(int,stdin.readline().split()))
n=L[0]
k=L[1]
#a=list(map(int,stdin.readline().split()))
a=[int(c) for c in stdin.readline().split()]
nbr0=0
posi=0
taillemax=0
p=0
for i in range(len(a)):
nbr0+=(a[i]==0)
if nbr0>k:
if (i-posi)>taillemax:
p=posi
taillemax=i-posi
j=posi
while 1:
if a[j]==0:
posi=j+1
break
j=j+1
nbr0-=1
if i==(n-1) and (i-posi+1)>taillemax:
p=posi
taillemax=i-posi+1
#print(p,posi)
print(taillemax)
ch=""
for i in range(len(a)):
if i>=p and i<(p+taillemax):
ch+="1 "
else:
ch+=str(a[i])+" "
stdout.write(ch)
``` | instruction | 0 | 32,111 | 12 | 64,222 |
Yes | output | 1 | 32,111 | 12 | 64,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
Submitted Solution:
```
import sys
import inspect
import re
import math
import collections
from pprint import pprint as pp
mod = 998244353
MAX = 10**15
def deb(p):
for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bdeb\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
print('%s %d' % (m.group(1), p))
def inp():
return map(int, input().split())
def array():
return list(map(int, input().split()))
def vector(size, val=0):
vec = [val for i in range(size)]
return vec
def matrix(rowNum, colNum, val=0):
mat = []
for i in range(rowNum):
collumn = [val for j in range(colNum)]
mat.append(collumn)
return mat
n, k = inp()
a = [0] + array()
dp = vector(n + 1)
dp0 = vector(n + 1)
for i in range(1, n + 1):
dp[i] = dp[i - 1] + (a[i] == 1)
dp0[i] = dp0[i - 1] + (a[i] == 0)
def fun(m):
for i in range(m, n + 1):
if dp[i] - dp[i - m] + min(k, dp0[i] - dp0[i - m]) >= m:
return True
return False
l, h, ans = 0, n, 0
while l <= h:
m = (l + h) // 2
if fun(m):
ans, l = m, m + 1
else:
h = m - 1
for i in range(ans, n + 1):
if dp[i] - dp[i - ans] + min(k, dp0[i] - dp0[i - m]) >= ans:
for j in range(i - m + 1, i + 1):
a[j] = 1
break
print(ans)
for i in range(1, n + 1):
print(a[i], end=' ')
``` | instruction | 0 | 32,112 | 12 | 64,224 |
No | output | 1 | 32,112 | 12 | 64,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
Submitted Solution:
```
n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
i,j,l=0,-1,0
z1,z2=0,-1
while i<n and j<n:
if l<k:
j+=1
if j<n:
l+=1-a[j]
else:
break
elif l==k:
if j-i+1>z2-z1+1:
z1,z2=i,j
j+=1
if j<n:
l+=1-a[j]
else:
break
else:
l-=1-a[i]
i+=1
print(z2-z1+1)
for i in range(z1,z2+1):
a[i]=1
print(*a)
``` | instruction | 0 | 32,113 | 12 | 64,226 |
No | output | 1 | 32,113 | 12 | 64,227 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
Submitted Solution:
```
import sys
input = sys.stdin.readline
def prog():
n,k = map(int,input().split())
a = list(map(int,input().split())) + [0]
count = 0
for i in range(n):
if a[i] == 1:
count += 1
if count + k >= n:
print(n)
print('1 '*n)
elif k == 0:
last = 0
mx = 0
for i in range(n):
if a[i] == 1 and a[i+1] == 0:
mx = max(mx, i - last +1)
if a[i] == 0 and a[i+1] == 1:
last = i + 1
print(mx)
a.pop()
print(*a)
else:
zero_locs = []
for i in range(n):
if a[i] == 0:
zero_locs.append(i)
suffix = [0]*(n+2)
prefix = [0]*(n+2)
last = 0
for i in range(n):
if a[i] == 1 and a[i+1] == 0:
suffix[i+1] = i - last + 1
prefix[last+1] = i - last + 1
if a[i] == 0 and a[i+1] == 1:
last = i + 1
'''
print(prefix)
print(suffix)
print(zero_locs)'''
mx = 0
best = k - 1
for r in range(k-1,len(zero_locs)):
print(r)
amt = zero_locs[r] - zero_locs[r - (k-1)] + 1 + suffix[zero_locs[r-(k-1)]] + prefix[zero_locs[r]]
if amt > mx:
mx = amt
best = r
a.pop()
'''print(best)
print(prefix)
print(suffix)'''
for i in range(zero_locs[best -(k-1)],zero_locs[best] + 1):
a[i] = 1
print(mx)
print(*a)
prog()
``` | instruction | 0 | 32,114 | 12 | 64,228 |
No | output | 1 | 32,114 | 12 | 64,229 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 β€ n β€ 3Β·105, 0 β€ k β€ n) β the number of elements in a and the parameter k.
The second line contains n integers ai (0 β€ ai β€ 1) β the elements of a.
Output
On the first line print a non-negative integer z β the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj β the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
Input
7 1
1 0 0 1 1 0 1
Output
4
1 0 0 1 1 1 1
Input
10 2
1 0 0 1 0 1 0 1 0 1
Output
5
1 0 0 1 1 1 1 1 0 1
Submitted Solution:
```
n,k=input().split(' ')
a=input().split(' ')
n=int(n)
L=[]
k=int(k)
L1=['0']
for j in range (len(a)) :
if int(a[j])==0:
L.append(j)
L.append(len(a)-1)
m=len(a[:L[k]])
L1=a.copy()
for h in range(L[k]):
L1[h]='1'
for j in range(1,len(L)-k-1):
if len(a[L[j-1]+1:L[j+k]])>m :
m=len(a[L[j-1]+1:L[j+k]])
L1=a.copy()
for h in range(len(L[j:j+k+1])):
L1[L[j]+h]='1'
j=len(L)-k-1
if len(a[L[j-1]+1:L[j+k]+1])>m :
m=len(a[L[j-1]+1:L[j+k]+1])
L1=a.copy()
for h in range(len(L[j:j+k+1])):
L1[L[j]+h]='1'
print(m)
if k>0 :
for j in range(len(L1)):
print(L1[j],end=' ')
else:
for j in range(len(a)):
print(a[j],end=' ')
``` | instruction | 0 | 32,115 | 12 | 64,230 |
No | output | 1 | 32,115 | 12 | 64,231 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k β₯ 0, 0 < r β€ 2k. Let's call that representation prairie partition of x.
For example, the prairie partitions of 12, 17, 7 and 1 are:
12 = 1 + 2 + 4 + 5,
17 = 1 + 2 + 4 + 8 + 2,
7 = 1 + 2 + 4,
1 = 1.
Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of numbers given from Alice to Borys.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1012; a1 β€ a2 β€ ... β€ an) β the numbers given from Alice to Borys.
Output
Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input.
If there are no such values of m, output a single integer -1.
Examples
Input
8
1 1 2 2 3 4 5 8
Output
2
Input
6
1 1 1 2 2 2
Output
2 3
Input
5
1 2 4 4 4
Output
-1
Note
In the first example, Alice could get the input sequence from [6, 20] as the original sequence.
In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3]. | instruction | 0 | 32,132 | 12 | 64,264 |
Tags: binary search, constructive algorithms, greedy, math
Correct Solution:
```
n = int(input())
a = sorted(list(map(int, input().split())))
maxe = max(a)
cnt = []
cur, k, i = 1, 0, 0
while i < n:
cnt.append(0)
while i < n and a[i] < cur:
cnt[2 * k] += 1
i += 1
cnt.append(0)
while i < n and a[i] == cur:
cnt[2 * k + 1] += 1
i += 1
k += 1
cur *= 2
cnt.append(0)
cnt.append(0)
maxe = len(cnt) - 1
maxk = cnt[1]
was = False
for l in range(maxk):
cur = 1
while cnt[cur] > 0:
cnt[cur] -= 1
cur += 2
cnt[cur] -= 1
cursum = 0
ok = True
for t in range(maxe, 0, -1):
cursum += cnt[t]
if cursum > 0:
ok = False
break
if ok:
print(l + 1, end=" ")
was = True
if not was:
print(-1)
# Made By Mostafa_Khaled
``` | output | 1 | 32,132 | 12 | 64,265 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k β₯ 0, 0 < r β€ 2k. Let's call that representation prairie partition of x.
For example, the prairie partitions of 12, 17, 7 and 1 are:
12 = 1 + 2 + 4 + 5,
17 = 1 + 2 + 4 + 8 + 2,
7 = 1 + 2 + 4,
1 = 1.
Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of numbers given from Alice to Borys.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1012; a1 β€ a2 β€ ... β€ an) β the numbers given from Alice to Borys.
Output
Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input.
If there are no such values of m, output a single integer -1.
Examples
Input
8
1 1 2 2 3 4 5 8
Output
2
Input
6
1 1 1 2 2 2
Output
2 3
Input
5
1 2 4 4 4
Output
-1
Note
In the first example, Alice could get the input sequence from [6, 20] as the original sequence.
In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3]. | instruction | 0 | 32,133 | 12 | 64,266 |
Tags: binary search, constructive algorithms, greedy, math
Correct Solution:
```
from collections import Counter
from math import log2
def can():
seqs_cp = Counter(seqs)
for num in set(nums):
cnt = nums[num]
while cnt != 0 and num < 2 ** 63:
dif = min(cnt, seqs_cp[num])
cnt -= dif
seqs_cp[num] -= dif
num *= 2
if cnt > 0:
return False
return True
n = int(input())
seq = list(map(int, input().split()))
cnt = Counter(seq)
nums = Counter(seq)
seqs = Counter()
cur_cnt = cnt[1]
cur_pow = 1
while cur_cnt != 0:
nums[cur_pow] -= cur_cnt
cur_pow *= 2
if cur_cnt > cnt[cur_pow]:
seqs[cur_pow // 2] = cur_cnt - cnt[cur_pow]
cur_cnt = cnt[cur_pow]
for num in set(nums):
addition = nums[num]
nums[num] = 0
nums[2 ** int(log2(num))] += addition
# remove elements with zero count
nums -= Counter()
seqs -= Counter()
cur_len = sum(seqs[num] for num in set(seqs))
res = []
cur_pow = 1
while can():
res.append(cur_len)
while seqs[cur_pow] == 0 and cur_pow <= 2 ** 63:
cur_pow *= 2
if cur_pow > 2 ** 63:
break
other_pow = 1
while other_pow <= cur_pow:
nums[other_pow] += 1
other_pow *= 2
seqs[cur_pow] -= 1
cur_len -= 1
print(-1 if len(res) == 0 else ' '.join(map(str, reversed(res))))
``` | output | 1 | 32,133 | 12 | 64,267 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k β₯ 0, 0 < r β€ 2k. Let's call that representation prairie partition of x.
For example, the prairie partitions of 12, 17, 7 and 1 are:
12 = 1 + 2 + 4 + 5,
17 = 1 + 2 + 4 + 8 + 2,
7 = 1 + 2 + 4,
1 = 1.
Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of numbers given from Alice to Borys.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1012; a1 β€ a2 β€ ... β€ an) β the numbers given from Alice to Borys.
Output
Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input.
If there are no such values of m, output a single integer -1.
Examples
Input
8
1 1 2 2 3 4 5 8
Output
2
Input
6
1 1 1 2 2 2
Output
2 3
Input
5
1 2 4 4 4
Output
-1
Note
In the first example, Alice could get the input sequence from [6, 20] as the original sequence.
In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3]. | instruction | 0 | 32,136 | 12 | 64,272 |
Tags: binary search, constructive algorithms, greedy, math
Correct Solution:
```
n = int(input())
a = sorted(list(map(int, input().split())))
maxe = max(a)
cnt = []
cur = 1
k = 0
i = 0
while i < n:
cnt.append(0)
while i < n and a[i] < cur:
cnt[2 * k] += 1
i += 1
cnt.append(0)
while i < n and a[i] == cur:
cnt[2 * k + 1] += 1
i += 1
k += 1
cur *= 2
cnt.append(0)
cnt.append(0)
maxe = len(cnt) - 1
maxk = cnt[1]
was = False
for l in range(maxk):
cur = 1
while cnt[cur] > 0:
cnt[cur] -= 1
cur += 2
cnt[cur] -= 1
cursum = 0
ok = True
for t in range(maxe, 0, -1):
cursum += cnt[t]
if cursum > 0:
ok = False
break
if ok:
print(l + 1, end=" ")
was = True
if not was:
print(-1)
``` | output | 1 | 32,136 | 12 | 64,273 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k β₯ 0, 0 < r β€ 2k. Let's call that representation prairie partition of x.
For example, the prairie partitions of 12, 17, 7 and 1 are:
12 = 1 + 2 + 4 + 5,
17 = 1 + 2 + 4 + 8 + 2,
7 = 1 + 2 + 4,
1 = 1.
Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of numbers given from Alice to Borys.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1012; a1 β€ a2 β€ ... β€ an) β the numbers given from Alice to Borys.
Output
Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input.
If there are no such values of m, output a single integer -1.
Examples
Input
8
1 1 2 2 3 4 5 8
Output
2
Input
6
1 1 1 2 2 2
Output
2 3
Input
5
1 2 4 4 4
Output
-1
Note
In the first example, Alice could get the input sequence from [6, 20] as the original sequence.
In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3]. | instruction | 0 | 32,137 | 12 | 64,274 |
Tags: binary search, constructive algorithms, greedy, math
Correct Solution:
```
from collections import Counter
from math import log2
MAX = 10 ** 12 + 1
def can():
seqs_cp = Counter(seqs)
for num in set(nums):
cnt = nums[num]
while cnt != 0 and num < MAX:
dif = min(cnt, seqs_cp[num])
cnt -= dif
seqs_cp[num] -= dif
num *= 2
if cnt > 0:
return False
return True
n = int(input())
seq = list(map(int, input().split()))
cnt = Counter(seq)
nums = Counter(seq)
seqs = Counter()
cur_cnt = cnt[1]
cur_pow = 1
while cur_cnt != 0:
nums[cur_pow] -= cur_cnt
cur_pow *= 2
if cur_cnt > cnt[cur_pow]:
seqs[cur_pow // 2] = cur_cnt - cnt[cur_pow]
cur_cnt = cnt[cur_pow]
for num in set(nums):
addition = nums[num]
nums[num] = 0
nums[2 ** int(log2(num))] += addition
# remove elements with zero count
nums -= Counter()
seqs -= Counter()
cur_len = sum(seqs[num] for num in set(seqs))
res = []
cur_pow = 1
while can():
res.append(cur_len)
while seqs[cur_pow] == 0 and cur_pow < MAX:
cur_pow *= 2
if cur_pow >= MAX:
break
other_pow = 1
while other_pow <= cur_pow:
nums[other_pow] += 1
other_pow *= 2
seqs[cur_pow] -= 1
cur_len -= 1
print(-1 if len(res) == 0 else ' '.join(map(str, reversed(res))))
``` | output | 1 | 32,137 | 12 | 64,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k β₯ 0, 0 < r β€ 2k. Let's call that representation prairie partition of x.
For example, the prairie partitions of 12, 17, 7 and 1 are:
12 = 1 + 2 + 4 + 5,
17 = 1 + 2 + 4 + 8 + 2,
7 = 1 + 2 + 4,
1 = 1.
Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of numbers given from Alice to Borys.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1012; a1 β€ a2 β€ ... β€ an) β the numbers given from Alice to Borys.
Output
Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input.
If there are no such values of m, output a single integer -1.
Examples
Input
8
1 1 2 2 3 4 5 8
Output
2
Input
6
1 1 1 2 2 2
Output
2 3
Input
5
1 2 4 4 4
Output
-1
Note
In the first example, Alice could get the input sequence from [6, 20] as the original sequence.
In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3]. | instruction | 0 | 32,138 | 12 | 64,276 |
Tags: binary search, constructive algorithms, greedy, math
Correct Solution:
```
from collections import Counter
n = int(input())
a = list(map(int, input().split()))
def get(cnt):
c = Counter(a)
last = []
while c[1] and (cnt is None or len(last) < cnt):
x = 1
while c[x]:
c[x] -= 1
x *= 2
last.append(x >> 1)
rem = sorted(c.elements())
i = 0
for x in last[::-1]:
if i < len(rem) and rem[i] < 2 * x:
i += 1
return len(last) if i == len(rem) else 0
mx = get(None)
lo, hi = 0, mx
while lo < hi:
mid = (lo + hi) >> 1
if get(mid):
hi = mid
else:
lo = mid + 1
if mx:
print(*range(lo, mx + 1))
else:
print(-1)
``` | output | 1 | 32,138 | 12 | 64,277 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2. | instruction | 0 | 32,530 | 12 | 65,060 |
Tags: implementation, sortings
Correct Solution:
```
# cook your dish here
n,k=map(int,input().split())
l=list(map(int,input().split()))
l=list(set(l))
l.sort()
val=0
for i in range(k):
if i>=len(l):
print(0)
else:
print(l[i]-val)
val=l[i]
``` | output | 1 | 32,530 | 12 | 65,061 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2. | instruction | 0 | 32,531 | 12 | 65,062 |
Tags: implementation, sortings
Correct Solution:
```
R = lambda: map(int, input().split())
n, k = R()
a = iter(sorted(set(R())))
p = 0
while k:
x = next(a, p)
print(x - p)
p = x
k -= 1
``` | output | 1 | 32,531 | 12 | 65,063 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2. | instruction | 0 | 32,532 | 12 | 65,064 |
Tags: implementation, sortings
Correct Solution:
```
n,k = tuple(map(int,input().split()))
arr = list(map(int,input().split()))
arr.sort()
sm = 0
for a in arr:
if a-sm!=0:
print(a-sm)
sm += (a-sm)
k-=1
if k==0: break
while k >0:
print(0)
k-=1
``` | output | 1 | 32,532 | 12 | 65,065 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2. | instruction | 0 | 32,533 | 12 | 65,066 |
Tags: implementation, sortings
Correct Solution:
```
N, K = map(int,input().split())
A = sorted(list(set(map(int, input().split()))))
j = 0
M = 0
for i in range(K):
if j >= len(A):
print("0")
continue
if A[j] - M > 0:
print(A[j]-M)
M+=A[j]-M
j+=1
else:
print("0")
j+=1
``` | output | 1 | 32,533 | 12 | 65,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2. | instruction | 0 | 32,534 | 12 | 65,068 |
Tags: implementation, sortings
Correct Solution:
```
n,k = map(int,input().split())
st = [0] + list(sorted(set(map(int,input().split()))))
print('\n'.join(['0' if i >= len(st) else str(st[i]-st[i-1]) for i in range(1,k+1)]))
``` | output | 1 | 32,534 | 12 | 65,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2. | instruction | 0 | 32,535 | 12 | 65,070 |
Tags: implementation, sortings
Correct Solution:
```
n , k = map(int,input().split())
l = list(map(int,input().split()))
l = list(set(l))
l.sort()
#print(l)
ans = []
ans.append(l[0])
for i in range(1 , len(l) , 1):
ans.append(l[i] - l[i - 1])
if(k < len(ans)):
for i in range(k):
print(ans[i])
else:
for i in range(len(ans)):
print(ans[i])
for i in range(k - len(ans)):
print(0)
#print(ans)
#kalay))
``` | output | 1 | 32,535 | 12 | 65,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2. | instruction | 0 | 32,536 | 12 | 65,072 |
Tags: implementation, sortings
Correct Solution:
```
n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
sa = set(a)
if 0 in sa:
sa.remove(0)
lsa = list(sa)
lsa.sort()
ds = 0
for i in range(k):
if i >= len(lsa):
print(0)
else:
print(lsa[i]-ds)
ds = lsa[i]
``` | output | 1 | 32,536 | 12 | 65,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2. | instruction | 0 | 32,537 | 12 | 65,074 |
Tags: implementation, sortings
Correct Solution:
```
from collections import deque
n, k = [int(p) for p in input().split()]
arr = sorted([int(p) for p in input().split()])
arr = deque(arr)
curr = 0
while arr and k > 0:
p = arr.popleft()
if p == curr:
continue
print(p-curr)
curr = p
k -= 1
while k:
print(0)
k -= 1
``` | output | 1 | 32,537 | 12 | 65,075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.