message stringlengths 2 43.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 853 107k | cluster float64 24 24 | __index_level_0__ int64 1.71k 214k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M). | instruction | 0 | 24,832 | 24 | 49,664 |
Tags: brute force, data structures, greedy, math
Correct Solution:
```
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
t=list(map(int,input().split()))
cnt=[0]*101
cs=0
ans=[]
for i in range(n):
r=cs-m+t[i]
res=0
if r>0:
for j in range(1,101)[::-1]:
if r-cnt[j]*j>0:
r-=cnt[j]*j
res+=cnt[j]
else:
res+=(r+j-1)//j
break
ans.append(res)
cs+=t[i]
cnt[t[i]]+=1
print(*ans)
``` | output | 1 | 24,832 | 24 | 49,665 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M). | instruction | 0 | 24,833 | 24 | 49,666 |
Tags: brute force, data structures, greedy, math
Correct Solution:
```
n, m = map(int, input().split())
c = [0] * 101
a = list(map(int,input().split()))
for i in range(n):
ans = 0
sm = a[i]
for j in range(1, 101):
k = min((m - sm) // j, c[j])
ans += k
sm += k * j
print(i - ans)
c[a[i]] += 1
``` | output | 1 | 24,833 | 24 | 49,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M). | instruction | 0 | 24,834 | 24 | 49,668 |
Tags: brute force, data structures, greedy, math
Correct Solution:
```
from itertools import accumulate
from collections import Counter
from bisect import bisect as br, bisect_left as bl
class PMS:
#1-indexed
def __init__(self, A, B, issum = False):
#Aに初期状態の要素をすべて入れる,Bは値域のリスト
self.X, self.comp = self.compress(B)
self.size = len(self.X)
self.tree = [0] * (self.size + 1)
self.p = 2**(self.size.bit_length() - 1)
self.dep = self.size.bit_length()
CA = Counter(A)
S = [0] + list(accumulate([CA[self.X[i]] for i in range(self.size)]))
for i in range(1, 1+self.size):
self.tree[i] = S[i] - S[i - (i&-i)]
if issum:
self.sumtree = [0] * (self.size + 1)
Ssum = [0] + list(accumulate([CA[self.X[i]]*self.X[i] for i in range(self.size)]))
for i in range(1, 1+self.size):
self.sumtree[i] = Ssum[i] - Ssum[i - (i&-i)]
def compress(self, L):
#座圧
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2, 1)}
# 1-indexed
return L2, C
def leng(self):
#今入っている個数を取得
return self.count(self.X[-1])
def count(self, i):
#i(Bの元)以下の個数を取得
i = self.comp[i]
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def less(self, v):
#v(Bの元である必要はない)未満の個数を取得
i = bl(self.X, v)
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def leq(self, v):
#v(Bの元である必要はない)以下の個数を取得
i = br(self.X, v)
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
#iをx個入れる,負のxで取り出す,iの個数以上取り出すとエラーを出さずにバグる
i = self.comp[i]
while i <= self.size:
self.tree[i] += x
i += i & -i
def get(self, v):
# v番目の値を取得
if v <= 0:
return -1
s = 0
k = self.p
for _ in range(self.dep):
if s + k <= self.size and self.tree[s+k] < v:
s += k
v -= self.tree[s]
k //= 2
return self.X[s]
def gets(self, v):
v1 = v
if v <= 0:
return 0
s = 0
k = self.p
for _ in range(self.dep):
if s + k <= self.size and self.sumtree[s+k] < v:
s += k
v -= self.sumtree[s]
k //= 2
if s == self.size:
return self.leng()
return self.count(self.X[s]) + (v1 - self.countsum(self.X[s]))//self.X[s]
def addsum(self, i, x):
#sumを扱いたいときにaddと併用
self.add(i, x)
x *= i
i = self.comp[i]
while i <= self.size:
self.sumtree[i] += x
i += i & -i
def countsum(self, i):
#i(Bの元)以下のsumを取得
i = self.comp[i]
s = 0
while i > 0:
s += self.sumtree[i]
i -= i & -i
return s
def getsum(self, v):
#v番目までのsumを取得
x = self.get(v)
return self.countsum(x) - x*(self.count(x) - v)
N, M = map(int, input().split())
T = list(map(int, input().split()))
S = PMS([T[0]], T, True)
print(0)
for i in range(1, N):
print(i - S.gets(M - T[i]))
S.addsum(T[i], 1)
``` | output | 1 | 24,834 | 24 | 49,669 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
Submitted Solution:
```
n, M = map(int, input().split())
a = list(map(int, input().split()))
b = [0] * 110
for x in a:
cc = 0
cur = 0
for j in range(1, 101):
h = min((M-x-cur)//j, b[j])
cc += h
cur += h * j
#print(h,cc,cur,(M-x-cur)//j," ",x)
b[x] += 1
#print()
print(sum(b) - cc - 1)
``` | instruction | 0 | 24,835 | 24 | 49,670 |
Yes | output | 1 | 24,835 | 24 | 49,671 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
Submitted Solution:
```
n, m = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))
cnt = [0]*101
curr = 0
for i in range(n):
res = 0
val = (curr+arr[i])-m
t = 100
while t > 0 and val > 0:
d = min(cnt[t], (val+t-1)//t)
res += d
val -= d*t
t -= 1
print(res, end=" ")
curr += arr[i]
cnt[arr[i]] += 1
``` | instruction | 0 | 24,836 | 24 | 49,672 |
Yes | output | 1 | 24,836 | 24 | 49,673 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
Submitted Solution:
```
from sys import stdin,stdout
from itertools import accumulate
import math
n,M=stdin.readline().strip().split(' ');n,M=int(n),int(M)
ti=list(map(int,stdin.readline().strip().split(' ')))
ps_ti=list(accumulate(ti))
tarr=[0 for i in range(101)]
ansarr=[]
for j in range(len(ti)):
if ps_ti[j]<=M:
ansarr.append('0');tarr[ti[j]]+=1
#print(ti[j],0)
else:
rm=0;diff=ps_ti[j]-M
#print(ti[j],diff,tarr)
for i in range(100,0,-1):
if tarr[i]==0:
continue
else:
if diff<=i*tarr[i]:
rm+=(math.ceil(diff/i))
break
else:
diff-=(i*tarr[i])
rm+=tarr[i]
ansarr.append(str(rm))
tarr[ti[j]]+=1
stdout.write(' '.join(ansarr))
``` | instruction | 0 | 24,837 | 24 | 49,674 |
Yes | output | 1 | 24,837 | 24 | 49,675 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
Submitted Solution:
```
from sys import stdout
n, m = map(int, input().split())
a = list(map(int, input().split()))
dp = 0
size = (max(a) + 1)
b = [0] * size
for i in range(n):
e = a[i]
k = 1
c = 0
s_c = m - e
while k < size:
if b[k] != 0:
if s_c < b[k] * k:
c += s_c // k
break
else:
s_c -= b[k] * k
c += b[k]
k += 1
b[e] += 1
stdout.write(str(i - c) + ' ')
``` | instruction | 0 | 24,838 | 24 | 49,676 |
Yes | output | 1 | 24,838 | 24 | 49,677 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
Submitted Solution:
```
import itertools
import heapq
n, m = map(int, input().split())
t = list(map(int, input().split()))
tsum = list(itertools.accumulate(t))
ans = []
for i in range(n):
if tsum[i] <= m:
ans.append(0)
else:
heap = [-k for k in t[:i]]
heapq.heapify(heap)
remain = sum(t[:i]) - m
count = 0
for j in range(i, n):
uselist = []
remain += t[j]
while remain > 0:
count += 1
use = heapq.heappop(heap)
remain += use
uselist.append(use)
else:
ans.append(count)
uselist.sort(reverse = True)
count -= len(uselist)
for uses in uselist[:100]:
heapq.heappush(heap, uses)
remain -= uses
heapq.heappush(heap, -t[j])
break
print(" ".join(map(str, ans)))
``` | instruction | 0 | 24,839 | 24 | 49,678 |
No | output | 1 | 24,839 | 24 | 49,679 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
Submitted Solution:
```
from itertools import accumulate
from collections import Counter
from bisect import bisect as br, bisect_left as bl
class PMS:
#1-indexed
def __init__(self, A, B, issum = False):
#Aに初期状態の要素をすべて入れる,Bは値域のリスト
self.X, self.comp = self.compress(B)
self.size = len(self.X)
self.tree = [0] * (self.size + 1)
self.p = 2**(self.size.bit_length() - 1)
self.dep = self.size.bit_length()
CA = Counter(A)
S = [0] + list(accumulate([CA[self.X[i]] for i in range(self.size)]))
for i in range(1, 1+self.size):
self.tree[i] = S[i] - S[i - (i&-i)]
if issum:
self.sumtree = [0] * (self.size + 1)
Ssum = [0] + list(accumulate([CA[self.X[i]]*self.X[i] for i in range(self.size)]))
for i in range(1, 1+self.size):
self.sumtree[i] = Ssum[i] - Ssum[i - (i&-i)]
def compress(self, L):
#座圧
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2, 1)}
# 1-indexed
return L2, C
def leng(self):
#今入っている個数を取得
return self.count(self.X[-1])
def count(self, i):
#i(Bの元)以下の個数を取得
i = self.comp[i]
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def less(self, v):
#v(Bの元である必要はない)未満の個数を取得
i = bl(self.X, v)
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def leq(self, v):
#v(Bの元である必要はない)以下の個数を取得
i = br(self.X, v)
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
#iをx個入れる,負のxで取り出す,iの個数以上取り出すとエラーを出さずにバグる
i = self.comp[i]
while i <= self.size:
self.tree[i] += x
i += i & -i
def get(self, v):
# v番目の値を取得
if v <= 0:
return -1
s = 0
k = self.p
for _ in range(self.dep):
if s + k <= self.size and self.tree[s+k] < v:
s += k
v -= self.tree[s]
k //= 2
return self.X[s]
def gets(self, v):
v1 = v
if v <= 0:
return -1
s = 0
k = self.p
for _ in range(self.dep):
if s + k <= self.size and self.sumtree[s+k] < v:
s += k
v -= self.sumtree[s]
k //= 2
if s == self.size:
return self.leng()
return self.count(self.X[s]) + (v1 - self.countsum(self.X[s]))//self.X[s]
def addsum(self, i, x):
#sumを扱いたいときにaddと併用
self.add(i, x)
x *= i
i = self.comp[i]
while i <= self.size:
self.sumtree[i] += x
i += i & -i
def countsum(self, i):
#i(Bの元)以下のsumを取得
i = self.comp[i]
s = 0
while i > 0:
s += self.sumtree[i]
i -= i & -i
return s
def getsum(self, v):
#v番目までのsumを取得
x = self.get(v)
return self.countsum(x) - x*(self.count(x) - v)
N, M = map(int, input().split())
T = list(map(int, input().split()))
S = PMS([T[0]], T, True)
print(0)
for i in range(1, N):
print(i - S.gets(M - T[i]))
S.addsum(T[i], 1)
``` | instruction | 0 | 24,840 | 24 | 49,680 |
No | output | 1 | 24,840 | 24 | 49,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
Submitted Solution:
```
import itertools
from heapq import heapify, heappush, heappop
n, m = map(int, input().split())
t = list(map(int, input().split()))
tsum = list(itertools.accumulate(t))
ans = []
for i in range(n):
if tsum[i] <= m:
ans.append(0)
else:
heap = [-k for k in t[:i]]
heapify(heap)
remain = sum(t[:i]) - m
count = 0
for j in range(i, n):
uselist = []
remain += t[j]
uselist_append = uselist.append
uselist_sort = uselist.sort
while remain > 0:
count += 1
use = heappop(heap)
remain += use
uselist_append(use)
else:
ans.append(count)
uselist_sort(reverse = True)
count -= min(len(uselist),90)
for uses in uselist[:90]:
heappush(heap, uses)
remain -= uses
heappush(heap, -t[j])
break
print(" ".join(map(str, ans)))
``` | instruction | 0 | 24,841 | 24 | 49,682 |
No | output | 1 | 24,841 | 24 | 49,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i ≤ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ M ≤ 2 ⋅ 10^7) — the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 ≤ t_i ≤ 100) — time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
Submitted Solution:
```
from sys import stdin, stdout, maxsize as mxs
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from typing import Counter
from itertools import accumulate
mod = pow(10, 9) + 7
mod2 = 998244353
def inp(): return stdin.readline().strip()
def iinp(): return int(inp())
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return map(int, inp().split())
def smp(): return map(str, inp().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)]
def remadd(x, y): return 1 if x%y else 0
def ceil(a,b): return (a+b-1)//b
def isprime(x):
if x<=1: return False
if x in (2, 3): return True
if x%2 == 0: return False
for i in range(3, int(sqrt(x))+1, 2):
if x%i == 0: return False
return True
class MaxHeap:
def __init__(self, maxsize):
self.maxsize = maxsize
self.size = 0
self.Heap = [0] * (self.maxsize + 1)
self.Heap[0] = mxs
self.FRONT = 1
# Function to return the position of
# parent for the node currently
# at pos
def parent(self, pos):
return pos // 2
# Function to return the position of
# the left child for the node currently
# at pos
def leftChild(self, pos):
return 2 * pos
# Function to return the position of
# the right child for the node currently
# at pos
def rightChild(self, pos):
return (2 * pos) + 1
# Function that returns true if the passed
# node is a leaf node
def isLeaf(self, pos):
if pos >= (self.size//2) and pos <= self.size:
return True
return False
# Function to swap two nodes of the heap
def swap(self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = (self.Heap[spos],
self.Heap[fpos])
# Function to heapify the node at pos
def maxHeapify(self, pos):
# If the node is a non-leaf node and smaller
# than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or
self.Heap[pos] < self.Heap[self.rightChild(pos)]):
# Swap with the left child and heapify
# the left child
if (self.Heap[self.leftChild(pos)] >
self.Heap[self.rightChild(pos)]):
self.swap(pos, self.leftChild(pos))
self.maxHeapify(self.leftChild(pos))
# Swap with the right child and heapify
# the right child
else:
self.swap(pos, self.rightChild(pos))
self.maxHeapify(self.rightChild(pos))
# Function to insert a node into the heap
def insert(self, element):
if self.size >= self.maxsize:
return
self.size += 1
self.Heap[self.size] = element
current = self.size
while (self.Heap[current] >
self.Heap[self.parent(current)]):
self.swap(current, self.parent(current))
current = self.parent(current)
# Function to print the contents of the heap
def Print(self):
for i in range(1, (self.size // 2) + 1):
print(" PARENT : " + str(self.Heap[i]) +
" LEFT CHILD : " + str(self.Heap[2 * i]) +
" RIGHT CHILD : " + str(self.Heap[2 * i + 1]))
# Function to remove and return the maximum
# element from the heap
def extractMax(self):
popped = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]
self.size -= 1
self.maxHeapify(self.FRONT)
return popped
n, k = mp()
arr = lmp()
ansl = []
ml = MaxHeap(2*n)
s = 0
c = 0
for i in range(n):
pl = []
ts = 0
while s>k-arr[i]:
x = ml.extractMax()
s -= x
c += 1
pl.append(x)
ts += x
ml.insert(arr[i])
s += arr[i]
for j in pl: ml.insert(j)
s += ts
ansl.append(c)
c = 0
print(*ansl)
``` | instruction | 0 | 24,842 | 24 | 49,684 |
No | output | 1 | 24,842 | 24 | 49,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp's phone book contains n phone numbers, each of them is described by s_i — the number itself and m_i — the number of times Polycarp dials it in daily.
Polycarp has just bought a brand new phone with an amazing speed dial feature! More precisely, k buttons on it can have a number assigned to it (not necessary from the phone book). To enter some number Polycarp can press one of these k buttons and then finish the number using usual digit buttons (entering a number with only digit buttons is also possible).
Speed dial button can only be used when no digits are entered. No button can have its number reassigned.
What is the minimal total number of digit number presses Polycarp can achieve after he assigns numbers to speed dial buttons and enters each of the numbers from his phone book the given number of times in an optimal way?
Input
The first line contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ 10) — the amount of numbers in Polycarp's phone book and the number of speed dial buttons his new phone has.
The i-th of the next n lines contain a string s_i and an integer m_i (1 ≤ m_i ≤ 500), where s_i is a non-empty string of digits from 0 to 9 inclusive (the i-th number), and m_i is the amount of times it will be dialed, respectively.
It is guaranteed that the total length of all phone numbers will not exceed 500.
Output
Print a single integer — the minimal total number of digit number presses Polycarp can achieve after he assigns numbers to speed dial buttons and enters each of the numbers from his phone book the given number of times in an optimal way.
Examples
Input
3 1
0001 5
001 4
01 1
Output
14
Input
3 1
0001 5
001 6
01 1
Output
18
Note
The only speed dial button in the first example should have "0001" on it. The total number of digit button presses will be 0 ⋅ 5 for the first number + 3 ⋅ 4 for the second + 2 ⋅ 1 for the third. 14 in total.
The only speed dial button in the second example should have "00" on it. The total number of digit button presses will be 2 ⋅ 5 for the first number + 1 ⋅ 6 for the second + 2 ⋅ 1 for the third. 18 in total.
Submitted Solution:
```
from functools import reduce
class Node:
def __init__(self, presses, depth):
self.presses = presses
self.depth = depth
self.children = {}
def get_reducing_factor(self):
return self.depth * self.presses
def process_number(number, presses, c_dict):
counter = 0
for digit in number:
counter += 1
if digit not in c_dict:
c_dict[digit] = Node(presses, counter)
else:
c_dict[digit].presses += presses
c_dict = c_dict[digit].children
def get_node_with_highest_reducing_factor(c_dict, c_num, current_reducing_factor = 0):
node_list = []
for key, node in c_dict.items():
c_num_after_key = c_num + key
rf = node.get_reducing_factor()
if rf > current_reducing_factor:
node_list.append((node, c_num_after_key))
current_reducing_factor = rf
node_list += get_node_with_highest_reducing_factor(node.children, c_num_after_key, current_reducing_factor)
return node_list
def remove_node(num, press, dct):
for digit in num:
node = dct[digit]
node.presses -= press
dct = node.children
if __name__ == '__main__':
primary_dict = {}
(n, k) = map(int, input().split(' '))
total_presses = 0
for i in range(n):
(num, press) = input().split(' ')
press = int(press)
total_presses += len(num) * press
process_number(num, press, primary_dict)
for i in range(k):
(node, num) = get_node_with_highest_reducing_factor(primary_dict, '')[-1]
total_presses -= node.get_reducing_factor()
remove_node(num, node.presses, primary_dict)
print(total_presses)
``` | instruction | 0 | 25,596 | 24 | 51,192 |
No | output | 1 | 25,596 | 24 | 51,193 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.
In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.
Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.
Input
The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.
Output
Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.
Examples
Input
4
3 6 12 24
Output
0
Input
4
-8 -16 24 -32
Output
1
Input
4
0 1 2 3
Output
2 | instruction | 0 | 26,006 | 24 | 52,012 |
Tags: implementation
Correct Solution:
```
def main():
n = int(input())
l = tuple(map(int, input().split()))
if n == 1:
return 0
if n == 2:
if l[0] == 0 and l[1] != 0: return 1
return 0
def div(a, b):
if b == 0: return 0 if a == 0 else "inf"
return a / b
pref, suff = [["init", 1]], [["init", 1]]
for i in range(1, n):
d = div(l[i], l[i-1])
if pref[-1][0] == "init":
pass
elif d != pref[-1][0]:
for j in range(i, n):
pref += [["null", 0]]
break
pref += [[d, 1]]
for i in range(n - 1, -1, -1):
d = div(l[i], l[i-1])
if l[i - 1] == 0 and l[i] != 0:
suff[-1][0] = suff[-2][0] if len(suff) > 1 else 1
if d != suff[-1][0] and suff[-1][0] != "init":
for j in range(i-1, -1,-1):
suff += [["null", 0]]
break
suff += [[d, 1]]
#print(pref)
#print(suff)
if pref[-1][1] == 1: return 0
if pref[-2][1] == 1 or suff[-2][1] == 1: return 1
for i in range(1,n-1):
pr, sf = pref[i - 1], suff[n - i - 2]
dv = div(l[i+1], l[i-1])
#print(pr,sf,dv,l[i-1:i+2])
if pr[0] == "init" and sf[0] == "init": return 1
if pr[0] == "init" and dv == sf[0]:
return 1
elif sf[0] == "init" and dv == pr[0]:
return 1
elif dv == pr[0] and dv == sf[0]:
return 1
return 2
print(main())
``` | output | 1 | 26,006 | 24 | 52,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.
In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.
Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.
Input
The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.
Output
Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.
Examples
Input
4
3 6 12 24
Output
0
Input
4
-8 -16 24 -32
Output
1
Input
4
0 1 2 3
Output
2
Submitted Solution:
```
def main():
n = int(input())
l = tuple(map(int, input().split()))
if n == 1:
return 0
if n == 2:
if l[0] == 0 and l[1] != 0: return 1
return 0
def div(a, b):
if b == 0: return 0 if a == 0 else "inf"
return a / b
pref, suff = [["init", 1]], [["init", 1]]
for i in range(1, n):
d = div(l[i], l[i-1])
if pref[-1][0] == "init":
pass
elif d != pref[-1][0]:
for j in range(i, n):
pref += [[0, 0]]
break
pref += [[d, 1]]
for i in range(n - 1, -1, -1):
d = div(l[i], l[i-1])
if suff[-1][0] == "init":
pass
elif d != suff[-1][0]:
for j in range(i-1, -1,-1):
suff += [[0, 0]]
break
suff += [[d, 1]]
if pref[-1][1] == 1: return 0
if pref[-2][1] == 1 or suff[-2][1] == 1: return 1
for i in range(1,n-1):
pr, sf = pref[i - 1], suff[n - i - 2]
dv = div(l[i+1], l[i-1])
if pr[0] == "init" and sf[0] == "init": return 1
if pr[0] == "init" and dv == sf[0]:
return 1
elif sf[0] == "init" and dv == pr[0]:
return 1
elif dv == pr[0] and dv == sf[0]:
return 1
return 2
print(main())
``` | instruction | 0 | 26,007 | 24 | 52,014 |
No | output | 1 | 26,007 | 24 | 52,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.
In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.
Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.
Input
The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.
Output
Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.
Examples
Input
4
3 6 12 24
Output
0
Input
4
-8 -16 24 -32
Output
1
Input
4
0 1 2 3
Output
2
Submitted Solution:
```
def main():
n = int(input())
l = tuple(map(int, input().split()))
if n == 1:
return 0
if n == 2:
if l[0] == 0 and l[1] != 0: return 1
return 0
def div(a, b):
if b == 0: return "inf"
return a / b
pref, suff = [["init", 1]], [["init", 1]]
for i in range(1, n):
d = div(l[i-1], l[i])
if pref[-1][0] == "init":
pass
elif d != pref[-1][0]:
for j in range(i, n):
pref += [[0, 0]]
break
pref += [[d, 1]]
for i in range(n - 1, -1, -1):
d = div(l[i], l[i - 1])
if suff[-1][0] == "init":
pass
elif d != suff[-1][0]:
for j in range(i-1, -1,-1):
suff += [[0, 0]]
break
suff += [[d, 1]]
if pref[-1][1] == 1: return 0
if pref[-2][1] == 1 or suff[-2][1] == 1: return 1
for i in range(1,n-1):
pr, sf = pref[i - 1], suff[n - i - 2]
dv = div(l[i-1], l[i+1])
if pr[0] == "init" and sf[0] == "init": return 1
if pr[0] == "init" and dv == sf[0]:
return 1
elif sf[0] == "init" and dv == pr[0]:
return 1
elif dv == pr[0] and dv == sf[0]:
return 1
return 2
print(main())
``` | instruction | 0 | 26,008 | 24 | 52,016 |
No | output | 1 | 26,008 | 24 | 52,017 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.
In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.
Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.
Input
The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.
Output
Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.
Examples
Input
4
3 6 12 24
Output
0
Input
4
-8 -16 24 -32
Output
1
Input
4
0 1 2 3
Output
2
Submitted Solution:
```
def main():
n = int(input())
l = tuple(map(int, input().split()))
if n == 1:
return 0
if n == 2:
if l[0] == 0 and l[1] != 0: return 1
return 0
def div(a, b):
if b == 0: return "inf"
return a / b
pref, suff = [["init", 1]], [["init", 1]]
for i in range(1, n):
d = div(l[i], l[i-1])
if pref[-1][0] == "init":
pass
elif d != pref[-1][0]:
for j in range(i, n):
pref += [[0, 0]]
break
pref += [[d, 1]]
for i in range(n - 1, -1, -1):
d = div(l[i], l[i-1])
if suff[-1][0] == "init":
pass
elif d != suff[-1][0]:
for j in range(i-1, -1,-1):
suff += [[0, 0]]
break
suff += [[d, 1]]
if pref[-1][1] == 1: return 0
if pref[-2][1] == 1 or suff[-2][1] == 1: return 1
for i in range(1,n-1):
pr, sf = pref[i - 1], suff[n - i - 2]
dv = div(l[i+1], l[i-1])
if pr[0] == "init" and sf[0] == "init": return 1
if pr[0] == "init" and dv == sf[0]:
return 1
elif sf[0] == "init" and dv == pr[0]:
return 1
elif dv == pr[0] and dv == sf[0]:
return 1
return 2
print(main())
``` | instruction | 0 | 26,009 | 24 | 52,018 |
No | output | 1 | 26,009 | 24 | 52,019 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.
In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.
Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.
Input
The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.
Output
Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.
Examples
Input
4
3 6 12 24
Output
0
Input
4
-8 -16 24 -32
Output
1
Input
4
0 1 2 3
Output
2
Submitted Solution:
```
def main():
n = int(input())
l = tuple(map(int, input().split()))
if n == 1:
return 0
if n == 2:
if l[0] == 0 and l[1] != 0: return 1
return 0
def div(a, b):
if b == 0: return 0 if a == 0 else "inf"
return a / b
pref, suff = [["init", 1]], [["init", 1]]
for i in range(1, n):
d = div(l[i], l[i-1])
if pref[-1][0] == "init":
pass
elif d != pref[-1][0]:
for j in range(i, n):
pref += [["null", 0]]
break
pref += [[d, 1]]
for i in range(n - 1, -1, -1):
d = div(l[i], l[i-1])
if l[i - 1] == 0 and l[i] != 0:
suff[-1][0] = 1
if d != suff[-1][0] and suff[-1][0] != "init":
for j in range(i-1, -1,-1):
suff += [["null", 0]]
break
suff += [[d, 1]]
#print(pref)
#print(suff)
if pref[-1][1] == 1: return 0
if pref[-2][1] == 1 or suff[-2][1] == 1: return 1
for i in range(1,n-1):
pr, sf = pref[i - 1], suff[n - i - 2]
dv = div(l[i+1], l[i-1])
#print(pr,sf,dv,l[i-1:i+2])
if pr[0] == "init" and sf[0] == "init": return 1
if pr[0] == "init" and dv == sf[0]:
return 1
elif sf[0] == "init" and dv == pr[0]:
return 1
elif dv == pr[0] and dv == sf[0]:
return 1
return 2
print(main())
``` | instruction | 0 | 26,010 | 24 | 52,020 |
No | output | 1 | 26,010 | 24 | 52,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | instruction | 0 | 26,673 | 24 | 53,346 |
Tags: data structures, hashing, implementation, math
Correct Solution:
```
for _ in range (int(input())):
n = int(input())
a = []
b = []
x = {}
cou1 = 0
cou2 = 0
cou3 = 0
cou4 = 0
for i in range(n):
s = input()
b.append(s)
x[s] = True
a.append(s[0] + s[-1])
if a[i] == '00':
cou1 += 1
elif a[i] == '11':
cou2 += 1
elif a[i] == '10':
cou3 += 1
else:
cou4 += 1
if cou4 + cou3 == 0:
if cou1 > 0 and cou2 > 0:
print(-1)
else:
print("0\n")
elif cou4 + cou3 == 1:
print ("0\n")
else:
if abs(cou4 - cou3) <= 1:
print("0\n")
else:
ans = []
if cou4 > cou3:
for i in range(n):
if a[i] == '01' and b[i][::-1] not in x:
cou4 -= 1
cou3 += 1
ans.append(i + 1)
if cou4 - cou3 <= 1:
break
elif cou4 < cou3:
for i in range(n):
if a[i] == '10' and b[i][::-1] not in x:
cou4 += 1
cou3 -= 1
ans.append(i + 1)
if cou3 - cou4 <= 1:
break
print(len(ans))
print(*ans)
``` | output | 1 | 26,673 | 24 | 53,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | instruction | 0 | 26,674 | 24 | 53,348 |
Tags: data structures, hashing, implementation, math
Correct Solution:
```
from functools import reduce
def solve():
n = int(input())
words = []
s01 = []
s10 = []
s00 = False
s11 = False
d1 = set()
d2 = set()
for i in range(n):
ss = input()
if (ss[0] == '0' and ss[-1] == '0'):s00 = True
if (ss[0] == '1' and ss[-1] == '1'):s11 = True
if (ss[0] == '0' and ss[-1] == '1'):
s01.append(i)
d1.add(ss)
if (ss[0] == '1' and ss[-1] == '0'):
s10.append(i)
d2.add(ss)
words.append(ss)
if (len(s01) == 0 and len(s10) == 0):
if (s00 == True and s11 == True):
print(-1)
return
else:
print(0, "")
return
chan = abs(len(s01) - len(s10)) // 2
p = 0
ans = []
for i in range(chan):
if (len(s01) > len(s10)):
while (words[s01[p]][::-1] in d2):
if (p < len(s01)-1):
p += 1
else:
print(-1)
return
ans.append(s01[p])
p += 1
else:
while (words[s10[p]][::-1] in d1):
if (p < len(s10)-1):
p += 1
else:
print(-1)
return
ans.append(s10[p])
p += 1
print(len(ans))
for i in ans:
print(i+1, end = " ")
print("")
t = int(input())
for i in range(t):
solve()
``` | output | 1 | 26,674 | 24 | 53,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | instruction | 0 | 26,675 | 24 | 53,350 |
Tags: data structures, hashing, implementation, math
Correct Solution:
```
# your code goes here
t = int(input())
for j in range(t):
#print(j)
n = int(input())
a = 0
b = 0
c = 0
d = 0
s = set()
li = []
for i in range(n):
st = input()
s.add(st)
li.append(st)
ans = []
if st[0] == '0' and st[-1] == '0':
a += 1
if st[0] == '0' and st[-1] == '1':
b += 1
if st[0] == '1' and st[-1] == '0':
c += 1
if st[0] == '1' and st[-1] == '1':
d += 1
if b == 0 and c == 0:
#print(a, b ,c ,d)
if a != 0 and d != 0:
print("-1")
continue
print("0")
continue
else:
if b > c:
i = 0
#print("HI")
while i < len(li) and abs(b - c) > 1:
if li[i][0] == '0' and li[i][-1] == '1':
if li[i][::-1] not in s:
b -= 1
c += 1
ans.append(i + 1)
i+=1
elif c > b:
i = 0
while i < len(li) and abs(c - b) > 1:
if li[i][0] == '1' and li[i][-1] == '0':
if li[i][::-1] not in s:
b += 1
c -= 1
ans.append(i + 1)
i+=1
if abs(b - c) > 1:
print("-1")
else:
print(len(ans))
for i in ans:
print(i, end=" ")
print()
``` | output | 1 | 26,675 | 24 | 53,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | instruction | 0 | 26,676 | 24 | 53,352 |
Tags: data structures, hashing, implementation, math
Correct Solution:
```
#https://codeforces.com/contest/1277/problem/D
def solve():
n = int(input())
can_not = set()
can_swap = []
wait = {}
flg_0 = False
flg_2 = False
for i in range(n):
s = input()
if s[0] == s[-1] and s[0] == '1': #2
flg_2 = True
can_not.add(2)
elif s[0] == s[-1] and s[0] == '0': #0
flg_0 = True
can_not.add(0)
elif s[0] != s[-1]:
wait[s] = i
num_0_1 = 0
num_1_0 = 0
type_ = [[], []]
for s in wait:
if s[::-1] in wait:
can_not.add(1)
else:
if s[0] == '0':
num_0_1 += 1
type_[0].append(wait[s])
else:
num_1_0 += 1
type_[1].append(wait[s])
if num_0_1 + num_1_0 == 0:
if len(can_not) == 3:
return 0, ''
if 0 in can_not and 2 in can_not:
return -1, None
return 0, ''
num = abs(num_0_1-num_1_0) // 2
if num == 0:
return 0, ''
else:
typ = 0 if num_0_1 > num_1_0 else 1
select = []
for x in type_[typ][:num]:
select.append(str(x+1))
return num, ' '.join([x for x in select])
for _ in range(int(input())):
num, ans = solve()
print(num)
if ans is not None:
print(ans)
#11
#001
#100
#1101
#1011
#0100
#0010
#1001
#010
#100
#1010
#10000
``` | output | 1 | 26,676 | 24 | 53,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | instruction | 0 | 26,677 | 24 | 53,354 |
Tags: data structures, hashing, implementation, math
Correct Solution:
```
def f():
n = int(input())
word01 = dict()
word10 = dict()
have00 = 0
have11 = 0
for i in range(n):
w = input()
tag = w[0]+w[-1]
if tag == '01':
word01[w] = i
elif tag == '10':
word10[w] = i
elif tag == '11':
have11 = 1
elif tag == '00':
have00 = 1
l01 = len(word01)
l10 = len(word10)
if l01==0 and l10 == 0:
if have11 and have00:
print(-1)
return
if l01 < l10:
word10, word01 = word01, word10
l10, l01 = l01, l10
# 01 is more than 10
if l01 - l10 < 2:
print(0)
print()
return
count = (l01 - l10)//2
changeIndex = []
for w in word01:
if count <= 0:
break
if w[::-1] in word10:
continue
changeIndex.append(word01[w])
count -= 1
print(len(changeIndex))
print(' '.join(str(s+1)for s in changeIndex))
t = int(input())
for i in range(t):
f()
``` | output | 1 | 26,677 | 24 | 53,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | instruction | 0 | 26,678 | 24 | 53,356 |
Tags: data structures, hashing, implementation, math
Correct Solution:
```
#Bhargey Mehta (Junior)
#DA-IICT, Gandhinagar
import sys, math
MOD = 10**9+7
#sys.stdin = open('input.txt', 'r')
for _ in range(int(input())):
n = int(input())
oo, zo, oz, zz = [], [], [], []
actual = []
act_set = set()
for i in range(n):
s = input()
actual.append(s)
act_set.add(s)
if s[0] == '0':
if s[-1] == '0':
zz.append(i+1)
else:
zo.append(i+1)
else:
if s[-1] == '0':
oz.append(i+1)
else:
oo.append(i+1)
if len(oz) == 0 and len(zo) == 0 and len(oo) != 0 and len(zz) != 0:
print(-1)
continue
oz.sort(key=lambda x: 1 if actual[x-1][::-1] in act_set else 0)
zo.sort(key=lambda x: 1 if actual[x-1][::-1] in act_set else 0)
while len(oz) > 0 and len(zo) > 0:
oz.pop(), zo.pop()
if len(oz) == 0: ans = zo[:len(zo)//2]
else: ans = oz[:len(oz)//2]
ok = True
for indx in ans:
if actual[indx-1][::-1] in act_set:
ok = False
break
print(len(ans))
print(*ans)
``` | output | 1 | 26,678 | 24 | 53,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | instruction | 0 | 26,679 | 24 | 53,358 |
Tags: data structures, hashing, implementation, math
Correct Solution:
```
import sys
from collections import defaultdict
input = sys.stdin.readline
t = int(input())
for _ in range(t):
N = int(input())
w00 = 0
w11 = 0
w01 = defaultdict(int)
w10 = defaultdict(int)
for i in range(1, N+1):
w = input().rstrip('\n')
if w[0] == w[-1] == '0':
w00 = 1
elif w[0] == w[-1] == '1':
w11 = 1
elif w[0] == '0':
w_rev = w[::-1]
w10[w_rev] = -1
if w01[w] == 0:
w01[w] = i
else:
w_rev = w[::-1]
w01[w_rev] = -1
if w10[w] == 0:
w10[w] = i
if w00 == w11 == 1:
if len(w01) == len(w10) == 0:
print(-1)
continue
ans = 0
i01 = []
i10 = []
for i in w01.values():
if i > 0:
i01.append(i)
for i in w10.values():
if i > 0:
i10.append(i)
if len(i01) > len(i10):
ans = i01[:(len(i01) - len(i10))//2]
else:
ans = i10[:(len(i10) - len(i01)) // 2]
print(len(ans))
print(*ans)
``` | output | 1 | 26,679 | 24 | 53,359 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2 | instruction | 0 | 26,680 | 24 | 53,360 |
Tags: data structures, hashing, implementation, math
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
s = [str()] * n
st = set()
cnt_11 = 0
cnt_00 = 0
patt_01 = []
patt_10 = []
for i in range(n):
s[i] = input()
if s[i][0] == s[i][-1]:
if s[i][0] == '0':
cnt_00 += 1
else:
cnt_11 += 1
else:
if s[i][0] == '0':
patt_01.append(i)
else:
patt_10.append(i)
st.add(s[i])
has_duo = [False] * n
for i in range(n):
if s[i][::-1] in st:
has_duo[i] = True
if (cnt_11 != 0 and cnt_00 != 0) and (len(patt_01) == 0 and len(patt_10) == 0):
print(-1)
continue
else:
cnt_01 = len(patt_01)
cnt_10 = len(patt_10)
if cnt_01 < cnt_10:
cnt_01, cnt_10 = cnt_10, cnt_01
patt_01, patt_10 = patt_10, patt_01
delta = (cnt_01 - cnt_10) // 2
rev = []
for patt in patt_01:
if delta == 0:
break
if not has_duo[patt]:
rev.append(patt + 1)
delta -= 1
if delta == 0:
print(len(rev))
print(*rev)
else:
print(-1)
``` | output | 1 | 26,680 | 24 | 53,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
Submitted Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
dic = {'01':[],'10':[],'11':[],'00':[]}
hash = {}
bits = []
for i in range(1,n+1):
s = input()
hash[s]=1
bits.append(s)
if s[0]=='0' and s[-1]=='1':
dic['01'].append(i)
elif s[0]=='1' and s[-1]=='0':
dic['10'].append(i)
elif s[0]=='1' and s[-1]=='1':
dic['11'].append(i)
else:
dic['00'].append(i)
a = len(dic['01'])
b = len(dic['10'])
c = len(dic['11'])
d = len(dic['00'])
res = 0
#only one kind if bits at s and e
if a==0 and b==0 and (c==0 or d==0):
print(0)
print("")
#impossible
elif a==0 and b==0:
print(-1)
else:
if a>b:
res = (a-b)//2
arr = []
ind=0
for e in dic['01']:
if ind==res:
break
rev= bits[e-1][::-1]
if rev not in hash or hash[rev]==0:
arr.append(e)
hash[rev]=1
hash[bits[e-1]]=0
ind+=1
else:
res = (b-a)//2
arr = []
ind=0
for e in dic['10']:
if ind==res:
break
rev = bits[e-1][::-1]
if rev not in hash or hash[rev]==0:
hash[rev]=1
hash[bits[e-1]]=0
arr.append(e)
ind+=1
if ind<res:
print(-1)
else:
print(res)
print(*arr)
``` | instruction | 0 | 26,681 | 24 | 53,362 |
Yes | output | 1 | 26,681 | 24 | 53,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
Submitted Solution:
```
def main():
N = int(input())
for _ in range(N):
L =int(input())
S = [str(input()) for _ in range(L)]
# 00, 11, 01, 10
a, b, c, d = 0, 0, 0, 0
C, D = {}, {}
for k in range(L):
e = S[k]
if e[0] == "0" and e[-1] == "0":
a += 1
elif e[0] == "1" and e[-1] == "1":
b += 1
elif e[0] == "0" and e[-1] == "1":
c += 1
C[e] = k+1
else:
d += 1
D[e] = k+1
if c == d == 0 and a * b > 0:
print(-1)
else:
diff = abs(c-d) // 2
print(diff)
if diff == 0:
print("")
else:
res = []
if c > d:
for e in C:
if e[::-1] not in D:
res.append(C[e])
if len(res) == diff:
break
else:
for e in D:
if e[::-1] not in C:
res.append(D[e])
if len(res) == diff:
break
print(*res)
if __name__ == "__main__":
main()
``` | instruction | 0 | 26,682 | 24 | 53,364 |
Yes | output | 1 | 26,682 | 24 | 53,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
Submitted Solution:
```
# n, x, a, b = map(int, input().split())
t = int(input())
for i in range(t):
d = {
'00': 0,
'01': 0,
'10': 0,
'11': 0
}
set_10 = set()
set_01 = set()
set_10_strings = set()
set_01_strings = set()
index2string = []
n = int(input())
for string_num in range(n):
s = input()
index2string.append(s)
key = s[0] + s[-1]
if key == '01':
set_01.add(string_num)
set_01_strings.add(s)
if key == '10':
set_10.add(string_num)
set_10_strings.add(s)
d[key] += 1
if (d['00'] > 0 and d['11'] > 0 and d['01'] == 0 and d['10'] == 0):
print(-1)
continue
if d['01'] > d['10']:
bigger_set = set_01
smaller_set = set_10_strings
else:
bigger_set = set_10
smaller_set = set_01_strings
bigger = max(d['01'], d['10'])
smaller = min(d['01'], d['10'])
ans = []
while bigger - smaller > 1:
for forward_string_index in bigger_set:
break
forward_string = index2string[forward_string_index]
backward_string = forward_string[::-1]
if backward_string in smaller_set:
bigger_set.discard(forward_string_index)
continue
else:
ans.append(str(forward_string_index + 1))
bigger_set.discard(forward_string_index)
bigger -= 2
print(len(ans))
print(' '.join(ans))
``` | instruction | 0 | 26,683 | 24 | 53,366 |
Yes | output | 1 | 26,683 | 24 | 53,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
Submitted Solution:
```
from sys import stdin, stdout
for cs in range(int(stdin.readline())):
n = int(stdin.readline())
cnt = [[] for _ in range(4)]
S = set()
rev_hash = []
for i in range(n):
s = stdin.readline().strip()
cnt[int(s[0])*2+int(s[-1])].append(i)
S.add(hash(s))
rev_hash.append(hash(s[::-1]))
if len(cnt[0] + cnt[3]) == n and len(cnt[0]) > 0 and len(cnt[3]) > 0:
stdout.write(f"-1\n")
else:
diff = len(cnt[1]) - len(cnt[2])
if diff < 0:
cnt[1], cnt[2] = cnt[2], cnt[1]
diff = abs(diff)
diff //= 2
ans = []
for i in cnt[1]:
if diff == 0:
break
if rev_hash[i] not in S:
diff -= 1
ans.append(i+1)
if diff != 0:
stdout.write(f"-1\n")
else:
ans = [str(_) for _ in ans]
stdout.write(f"{len(ans)}\n")
stdout.write(' '.join(ans) + '\n')
``` | instruction | 0 | 26,684 | 24 | 53,368 |
Yes | output | 1 | 26,684 | 24 | 53,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
Submitted Solution:
```
# your code goes here
t = int(input())
for i in range(t):
n = int(input())
a = 0
b = 0
c = 0
d = 0
s = set()
li = []
for i in range(n):
st = input()
s.add(st)
li.append(st)
if st[0] == '0' and st[-1] == '0':
a += 1
if st[0] == '0' and st[-1] == '1':
b += 1
if st[0] == '1' and st[-1] == '0':
c += 1
if st[0] == '1' and st[-1] == '1':
d += 1
if b == 0 and c == 0:
#print(a, b ,c ,d)
if a != 0 and d != 0:
print("-1")
continue
print("0")
continue
else:
if b > c:
i = 0
ans = []
#print("HI")
while i < len(li) and abs(b - c) > 1:
if li[i][0] == '0' and li[i][-1] == '1':
if li[i][::-1] not in s:
b -= 1
c += 1
ans.append(i + 1)
i+=1
elif c > b:
i = 0
ans = []
while i < len(li) and abs(c - b) > 1:
if li[i][0] == '1' and li[i][-1] == '0':
if li[i][::-1] not in s:
b += 1
c -= 1
ans.append(i + 1)
i+=1
if abs(b - c) > 1:
print("-1")
else:
print(len(ans))
for i in ans:
print(i, end=" ")
print()
``` | instruction | 0 | 26,685 | 24 | 53,370 |
No | output | 1 | 26,685 | 24 | 53,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def ctd(chr): return ord(chr)-ord("a")
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
for _ in range(N()):
n = N()
dic = {'11': 0, '00': 0, '10': 0, '01': 0}
ind1 = []
ind2 = []
for i in range(n):
s = input()
if s[0]=='1' and s[-1]=='1': dic['11']+=1
if s[0]=='0' and s[-1]=='0': dic['00']+=1
if s[0]=='1' and s[-1]=='0': dic['10']+=1; ind1.append(i+1)
if s[0]=='0' and s[-1]=='1': dic['01']+=1; ind2.append(i+1)
if dic['10']==0 and dic['01']==0:
print(0 if dic['11']==0 or dic['00']==0 else -1)
else:
dif = abs(len(ind1)-len(ind2))
if dif%2!=0 and dif!=1:
print(-1)
else:
print(dif//2)
if ind1>ind2:
print(*ind1[:dif//2])
else:
print(*ind2[:dif//2])
if __name__ == "__main__":
main()
``` | instruction | 0 | 26,686 | 24 | 53,372 |
No | output | 1 | 26,686 | 24 | 53,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
n = int(ri())
cnt00,cnt11,cnt01,cnt10 = 0,0,0,0
lis01 = []
lis10 = []
s01,s10 = set(),set()
for i in range(n):
temp = ri()
if temp[0] == temp[-1]:
if temp[0] == '1':
cnt11+=1
else:
cnt00+=1
else:
if temp[0] == '1':
lis10.append((i,temp))
s10.add(temp)
cnt10+=1
else:
lis01.append((i,temp))
s01.add(temp)
cnt01+=1
if cnt10 == 0 and cnt01 == 0 and cnt11 !=0 and cnt00 != 0:
print(-1)
else:
ans = []
flag = True
if cnt01 > cnt10:
temp = 0
while cnt01 > cnt10+1:
# print(lis01[temp][1][::-1], s10)
while temp < len(lis01[temp]) and lis01[temp][1][::-1] in s10:
temp+=1
if temp >= len(lis01[temp]):
flag = False
break
ans.append(lis01[temp][0]+1)
temp+=1
cnt01-=1
cnt10+=1
elif cnt10 > cnt01:
temp = 0
while cnt10 > cnt01+1:
while temp < len(lis10[temp]) and lis10[temp][1][::-1] in s01:
temp+=1
if temp >= len(lis10[temp]):
flag = False
break
ans.append(lis10[temp][0]+1)
temp+=1
cnt10-=1
cnt01+=1
if flag :
print(len(ans))
print(*ans)
else:
print(-1)
``` | instruction | 0 | 26,687 | 24 | 53,374 |
No | output | 1 | 26,687 | 24 | 53,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".
Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".
Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:
* the final set of n words still contains different words (i.e. all words are unique);
* there is a way to put all words of the final set of words in the order so that the final sequence of n words is consistent with the game rules.
Polycarp wants to reverse minimal number of words. Please, help him.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
The first line of a test case contains one integer n (1 ≤ n ≤ 2⋅10^5) — the number of words in the Polycarp's set. Next n lines contain these words. All of n words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed 4⋅10^6. All words are different.
Guaranteed, that the sum of n for all test cases in the input doesn't exceed 2⋅10^5. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed 4⋅10^6.
Output
Print answer for all of t test cases in the order they appear.
If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain k (0 ≤ k ≤ n) — the minimal number of words in the set which should be reversed. The second line of the output should contain k distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from 1 to n in the order they appear. If k=0 you can skip this line (or you can print an empty line). If there are many answers you can print any of them.
Example
Input
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001
Output
1
3
-1
0
2
1 2
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def ctd(chr): return ord(chr)-ord("a")
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
for _ in range(N()):
n = N()
arr = []
for _ in range(n): arr.append(input())
res, res1 = 0, 1
rec = [arr[0]]
rec1 = [arr[0][::-1]]
ind1 = []
ind2 = [1]
ta, tb = True, True
for i in range(1, n):
now = arr[i]
if now[0]==rec[-1][-1]:
rec.append(now)
elif now[0]!=rec[-1][-1]:
if now[-1]!=rec[-1][-1]: ta = False
rec.append(now[::-1])
ind1.append(i+1)
res+=1
if now[0]==rec1[-1][-1]:
rec1.append(now)
elif now[0]!=rec1[-1][-1]:
if now[-1] != rec1[-1][-1]: tb = False
rec1.append(now[::-1])
res1+=1
ind2.append(i+1)
ret = INF
retc = []
if ta:
ret = res
retc = ind1
if tb:
if res1<ret:
ret = res1
retc = ind2
if ret==INF:
print(-1)
else:
print(ret)
print(*retc)
if __name__ == "__main__":
main()
``` | instruction | 0 | 26,688 | 24 | 53,376 |
No | output | 1 | 26,688 | 24 | 53,377 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5 | instruction | 0 | 28,729 | 24 | 57,458 |
Tags: dp, greedy
Correct Solution:
```
n,k=map(int,input().split())
*l,=map(int,input().split())
a=0
for i in range(1,n):
two=l[i]+l[i-1]
if two<k:
l[i]+=k-two
a+=k-two
print(a)
print(' '.join(map(str,l)))
``` | output | 1 | 28,729 | 24 | 57,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5 | instruction | 0 | 28,730 | 24 | 57,460 |
Tags: dp, greedy
Correct Solution:
```
from sys import stdin as fin
# fin = open("cfr377b.in")
# n = int(fin.readline())
n, k = map(int, fin.readline().split())
arr = list(map(int, fin.readline().split()))
# line = fin.readline()
cnt = 0
for i in range(1, n):
inc = k - (arr[i] + arr[i - 1])
if inc > 0:
arr[i] += inc
cnt += inc
print(cnt)
print(' '.join(str(x) for x in arr))
``` | output | 1 | 28,730 | 24 | 57,461 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5 | instruction | 0 | 28,731 | 24 | 57,462 |
Tags: dp, greedy
Correct Solution:
```
arr = []
n,k = map(int, input().split())
arr = list(map(int,input().split()))
tot = 0
for i in range(1,n):
if(arr[i] + arr[i-1] < k):
tot += k - arr[i] - arr[i-1]
arr[i] = k - arr[i-1]
print(tot)
print(arr[0],end="")
for i in range(1,n):
print("",arr[i],end="")
``` | output | 1 | 28,731 | 24 | 57,463 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5 | instruction | 0 | 28,732 | 24 | 57,464 |
Tags: dp, greedy
Correct Solution:
```
n, k = map(int, input().split())
arr = list(map(int, input().split()))
cnt = 0
for i in range(n-1):
tmp = arr[i] + arr[i+1]
if tmp < k:
arr[i+1] += k - tmp
cnt += k - tmp
print(cnt)
print(' '.join(str(i) for i in arr))
``` | output | 1 | 28,732 | 24 | 57,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5 | instruction | 0 | 28,733 | 24 | 57,466 |
Tags: dp, greedy
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().strip()
inp = lambda: list(map(int,input().split()))
n,k = inp()
a = inp()
ans = float('inf')
prev = k
res = 0
for i in range(n):
temp = k-prev-a[i]
if temp>0:
a[i]+=temp
res+=temp
prev = a[i]
print(res)
print(*a)
``` | output | 1 | 28,733 | 24 | 57,467 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5 | instruction | 0 | 28,734 | 24 | 57,468 |
Tags: dp, greedy
Correct Solution:
```
n, k = map(int, input().split())
lst = list(map(int, input().split()))
res = 0
for i in range(1, n):
if lst[i] + lst[i - 1] < k:
res += k - (lst[i] + lst[i - 1])
lst[i] += k - (lst[i] + lst[i - 1])
print(res)
print(*lst)
``` | output | 1 | 28,734 | 24 | 57,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5 | instruction | 0 | 28,735 | 24 | 57,470 |
Tags: dp, greedy
Correct Solution:
```
inp = lambda: map(int, input().rstrip().split())
n, k = inp()
a = list(inp())
b = [a[0]]
for i in range(1,n):
x = max(a[i], k - b[-1])
b.append(x)
print(sum(b) - sum(a))
print(*b)
``` | output | 1 | 28,735 | 24 | 57,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5 | instruction | 0 | 28,736 | 24 | 57,472 |
Tags: dp, greedy
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = [0 for i in range(n)]
for i in range(1, n):
b[i] = max(k - a[i - 1] - a[i] - b[i - 1], 0)
print(sum(b))
for i in range(n):
print(a[i] + b[i], end=" ")
``` | output | 1 | 28,736 | 24 | 57,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Submitted Solution:
```
n,k=[int(x) for x in input().split()]
l=[int(x) for x in input().split()]
c=0
for i in range(1,n):
if (l[i]+l[i-1])<k:
c+=k-(l[i]+l[i-1])
l[i]+=k-(l[i]+l[i-1])
print(c)
for i in l:
print(i,end=" ")
``` | instruction | 0 | 28,737 | 24 | 57,474 |
Yes | output | 1 | 28,737 | 24 | 57,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Submitted Solution:
```
n,k=map(int,input().split())
a=list(map(int,input().split()))
c=0
for i in range(1,n):
if a[i]+a[i-1]<k:
c=c+(k-a[i]-a[i-1])
a[i]=a[i]+(k-a[i]-a[i-1])
print(c)
for i in a:
print(i,end=" ")
``` | instruction | 0 | 28,738 | 24 | 57,476 |
Yes | output | 1 | 28,738 | 24 | 57,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Submitted Solution:
```
# cook your dish here
n,k=map(int,input().split(' '))
s = list(map(int,input().split(' ')))
d=0
counter=0
for i in range(len(s)-1):
#print(i)
if(s[i]+s[i+1]<k):
t=s[i]+s[i+1]
#print("the value of t is:")
#print(t)
#print("the value of d is:")
d = k-t
counter+=d
#print(d)
s[i+1]=s[i+1]+d
#print("the value of s[i+1] is:")
#print(s[i+1])
print(counter)
for i in range(len(s)):
print(s[i],end=" ")
``` | instruction | 0 | 28,739 | 24 | 57,478 |
Yes | output | 1 | 28,739 | 24 | 57,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Submitted Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
for i in range(1, n):
diff = k - (a[i] + a[i - 1])
if diff > 0:
a[i] += diff
ans += diff
print(ans)
print(' '.join(map(str, a)))
``` | instruction | 0 | 28,740 | 24 | 57,480 |
Yes | output | 1 | 28,740 | 24 | 57,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Submitted Solution:
```
n,k = [int(i) for i in input().split()]
a = [int(k) for k in input().split()]
s = 0
if n == 1 :
if a[0] < k:
print (k-a[0])
print (k)
else:
print (0)
print (a[0])
for i in range(1,n):
if a[i]+a[i-1] < k:
temp = k - (a[i]+a[i-1])
s+=temp
a[i] = a[i]+temp
print (s)
print (*a)
``` | instruction | 0 | 28,741 | 24 | 57,482 |
No | output | 1 | 28,741 | 24 | 57,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Submitted Solution:
```
ii=lambda: int(input())
iin=lambda: map(int,input().split())
il=lambda: list(map(int,input().split()))
n,m=iin()
a=il()
if(n==1):
ans=max(0,m-a[0])
a[0]=max(a[0],m-a[0])
else:
ans=0
for i in range(1,n):
if(a[i]+a[i-1]<m):
ans+=m-a[i]-a[i-1]
a[i]=m-a[i-1]
print(ans)
print(*a)
``` | instruction | 0 | 28,742 | 24 | 57,484 |
No | output | 1 | 28,742 | 24 | 57,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Submitted Solution:
```
n, k = list(map(int, input().split()))
days = list(map(int, input().split()))
overoll_cost = 0
if n == 1 and days[0] < k:
overoll_cost = k - days[0]
days[0] = k
for day_index in range(1, n):
walked_num = days[day_index] + days[day_index - 1]
if walked_num < k:
overoll_cost += k - walked_num
days[day_index] += k - walked_num
print(overoll_cost)
print(' '.join(map(str, days)))
``` | instruction | 0 | 28,743 | 24 | 57,486 |
No | output | 1 | 28,743 | 24 | 57,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.
Output
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.
Examples
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Submitted Solution:
```
n,k=map(int,input().split())
l=list(map(int,input().split()))
if n==1:
print(0)
print(l[0])
else:
cnt=0
for i in range(1,len(l)):
if l[i]+l[i-1]<k:
l[i]=k-(l[i]+l[i-1])
cnt+=l[i]
print(cnt)
print(*l)
``` | instruction | 0 | 28,744 | 24 | 57,488 |
No | output | 1 | 28,744 | 24 | 57,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 ≤ n, a, b, c ≤ 4000) — the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number — the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2. | instruction | 0 | 29,389 | 24 | 58,778 |
Tags: brute force, dp
Correct Solution:
```
n, a, b, c = map(int, input().split())
ans = 0
for x in range(n + 1):
for y in range(n + 1):
k = n - a * x - b * y
if k < 0 or k % c != 0:
continue
z = k // c
if x + y + z > ans:
ans = x + y + z
print(ans)
``` | output | 1 | 29,389 | 24 | 58,779 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.