text stringlengths 1.02k 43.5k | conversation_id int64 853 107k | embedding list | cluster int64 24 24 |
|---|---|---|---|
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).
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)
```
| 24,832 | [
0.5673828125,
0.044708251953125,
0.045196533203125,
0.1785888671875,
-0.34423828125,
-0.2666015625,
-0.419921875,
0.023834228515625,
-0.1485595703125,
0.8837890625,
0.82421875,
0.049713134765625,
0.3330078125,
-0.99951171875,
-0.43212890625,
0.197509765625,
-0.83203125,
-0.44995117... | 24 |
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).
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
```
| 24,833 | [
0.5673828125,
0.044708251953125,
0.045196533203125,
0.1785888671875,
-0.34423828125,
-0.2666015625,
-0.419921875,
0.023834228515625,
-0.1485595703125,
0.8837890625,
0.82421875,
0.049713134765625,
0.3330078125,
-0.99951171875,
-0.43212890625,
0.197509765625,
-0.83203125,
-0.44995117... | 24 |
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).
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)
```
| 24,834 | [
0.5673828125,
0.044708251953125,
0.045196533203125,
0.1785888671875,
-0.34423828125,
-0.2666015625,
-0.419921875,
0.023834228515625,
-0.1485595703125,
0.8837890625,
0.82421875,
0.049713134765625,
0.3330078125,
-0.99951171875,
-0.43212890625,
0.197509765625,
-0.83203125,
-0.44995117... | 24 |
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)
```
Yes
| 24,835 | [
0.7236328125,
0.105712890625,
0.093017578125,
0.138916015625,
-0.3916015625,
-0.1964111328125,
-0.3916015625,
0.01401519775390625,
-0.2215576171875,
0.95068359375,
0.74462890625,
0.037994384765625,
0.290771484375,
-0.93798828125,
-0.3623046875,
0.092529296875,
-0.7744140625,
-0.502... | 24 |
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
```
Yes
| 24,836 | [
0.7236328125,
0.105712890625,
0.093017578125,
0.138916015625,
-0.3916015625,
-0.1964111328125,
-0.3916015625,
0.01401519775390625,
-0.2215576171875,
0.95068359375,
0.74462890625,
0.037994384765625,
0.290771484375,
-0.93798828125,
-0.3623046875,
0.092529296875,
-0.7744140625,
-0.502... | 24 |
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))
```
Yes
| 24,837 | [
0.7236328125,
0.105712890625,
0.093017578125,
0.138916015625,
-0.3916015625,
-0.1964111328125,
-0.3916015625,
0.01401519775390625,
-0.2215576171875,
0.95068359375,
0.74462890625,
0.037994384765625,
0.290771484375,
-0.93798828125,
-0.3623046875,
0.092529296875,
-0.7744140625,
-0.502... | 24 |
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) + ' ')
```
Yes
| 24,838 | [
0.7236328125,
0.105712890625,
0.093017578125,
0.138916015625,
-0.3916015625,
-0.1964111328125,
-0.3916015625,
0.01401519775390625,
-0.2215576171875,
0.95068359375,
0.74462890625,
0.037994384765625,
0.290771484375,
-0.93798828125,
-0.3623046875,
0.092529296875,
-0.7744140625,
-0.502... | 24 |
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)))
```
No
| 24,839 | [
0.7236328125,
0.105712890625,
0.093017578125,
0.138916015625,
-0.3916015625,
-0.1964111328125,
-0.3916015625,
0.01401519775390625,
-0.2215576171875,
0.95068359375,
0.74462890625,
0.037994384765625,
0.290771484375,
-0.93798828125,
-0.3623046875,
0.092529296875,
-0.7744140625,
-0.502... | 24 |
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)
```
No
| 24,840 | [
0.7236328125,
0.105712890625,
0.093017578125,
0.138916015625,
-0.3916015625,
-0.1964111328125,
-0.3916015625,
0.01401519775390625,
-0.2215576171875,
0.95068359375,
0.74462890625,
0.037994384765625,
0.290771484375,
-0.93798828125,
-0.3623046875,
0.092529296875,
-0.7744140625,
-0.502... | 24 |
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)))
```
No
| 24,841 | [
0.7236328125,
0.105712890625,
0.093017578125,
0.138916015625,
-0.3916015625,
-0.1964111328125,
-0.3916015625,
0.01401519775390625,
-0.2215576171875,
0.95068359375,
0.74462890625,
0.037994384765625,
0.290771484375,
-0.93798828125,
-0.3623046875,
0.092529296875,
-0.7744140625,
-0.502... | 24 |
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)
```
No
| 24,842 | [
0.7236328125,
0.105712890625,
0.093017578125,
0.138916015625,
-0.3916015625,
-0.1964111328125,
-0.3916015625,
0.01401519775390625,
-0.2215576171875,
0.95068359375,
0.74462890625,
0.037994384765625,
0.290771484375,
-0.93798828125,
-0.3623046875,
0.092529296875,
-0.7744140625,
-0.502... | 24 |
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)
```
No
| 25,596 | [
0.480224609375,
0.053131103515625,
0.042205810546875,
0.07373046875,
-0.55078125,
-0.485595703125,
-0.42138671875,
0.180419921875,
0.1951904296875,
0.85888671875,
0.611328125,
0.05084228515625,
-0.0135650634765625,
-0.517578125,
-0.399169921875,
0.1865234375,
-0.476806640625,
-0.52... | 24 |
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
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())
```
| 26,006 | [
0.47509765625,
0.08050537109375,
0.056854248046875,
0.343994140625,
-0.2352294921875,
-0.1365966796875,
-0.4384765625,
-0.1348876953125,
0.405517578125,
1.1123046875,
0.58642578125,
0.1103515625,
0.1673583984375,
-1.1435546875,
-0.8603515625,
-0.050689697265625,
-1.0576171875,
-1.1... | 24 |
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())
```
No
| 26,007 | [
0.450927734375,
0.08868408203125,
-0.002468109130859375,
0.282958984375,
-0.269775390625,
0.051788330078125,
-0.5400390625,
-0.016571044921875,
0.3515625,
1.119140625,
0.5625,
0.09222412109375,
0.08917236328125,
-1.0859375,
-0.85595703125,
-0.02880859375,
-1.033203125,
-1.176757812... | 24 |
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())
```
No
| 26,008 | [
0.482421875,
0.104736328125,
0.01708984375,
0.277587890625,
-0.275146484375,
0.05267333984375,
-0.55859375,
-0.0267791748046875,
0.36376953125,
1.0888671875,
0.5634765625,
0.0960693359375,
0.08953857421875,
-1.08984375,
-0.87255859375,
-0.03131103515625,
-1.0205078125,
-1.176757812... | 24 |
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())
```
No
| 26,009 | [
0.482421875,
0.10357666015625,
0.0175018310546875,
0.27880859375,
-0.274658203125,
0.054656982421875,
-0.55908203125,
-0.028564453125,
0.3623046875,
1.0888671875,
0.56396484375,
0.09332275390625,
0.09136962890625,
-1.08984375,
-0.87451171875,
-0.032379150390625,
-1.01953125,
-1.177... | 24 |
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())
```
No
| 26,010 | [
0.450927734375,
0.08868408203125,
-0.002468109130859375,
0.282958984375,
-0.269775390625,
0.051788330078125,
-0.5400390625,
-0.016571044921875,
0.3515625,
1.119140625,
0.5625,
0.09222412109375,
0.08917236328125,
-1.0859375,
-0.85595703125,
-0.02880859375,
-1.033203125,
-1.176757812... | 24 |
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
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)
```
| 26,673 | [
0.357177734375,
-0.09136962890625,
0.25732421875,
0.08880615234375,
-0.156494140625,
-0.634765625,
-0.34814453125,
-0.10284423828125,
-0.39306640625,
0.84423828125,
1.10546875,
-0.27685546875,
-0.03118896484375,
-0.71240234375,
-0.630859375,
-0.275146484375,
-0.5673828125,
-0.61962... | 24 |
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
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()
```
| 26,674 | [
0.357177734375,
-0.09136962890625,
0.25732421875,
0.08880615234375,
-0.156494140625,
-0.634765625,
-0.34814453125,
-0.10284423828125,
-0.39306640625,
0.84423828125,
1.10546875,
-0.27685546875,
-0.03118896484375,
-0.71240234375,
-0.630859375,
-0.275146484375,
-0.5673828125,
-0.61962... | 24 |
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
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()
```
| 26,675 | [
0.357177734375,
-0.09136962890625,
0.25732421875,
0.08880615234375,
-0.156494140625,
-0.634765625,
-0.34814453125,
-0.10284423828125,
-0.39306640625,
0.84423828125,
1.10546875,
-0.27685546875,
-0.03118896484375,
-0.71240234375,
-0.630859375,
-0.275146484375,
-0.5673828125,
-0.61962... | 24 |
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
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
```
| 26,676 | [
0.357177734375,
-0.09136962890625,
0.25732421875,
0.08880615234375,
-0.156494140625,
-0.634765625,
-0.34814453125,
-0.10284423828125,
-0.39306640625,
0.84423828125,
1.10546875,
-0.27685546875,
-0.03118896484375,
-0.71240234375,
-0.630859375,
-0.275146484375,
-0.5673828125,
-0.61962... | 24 |
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
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()
```
| 26,677 | [
0.357177734375,
-0.09136962890625,
0.25732421875,
0.08880615234375,
-0.156494140625,
-0.634765625,
-0.34814453125,
-0.10284423828125,
-0.39306640625,
0.84423828125,
1.10546875,
-0.27685546875,
-0.03118896484375,
-0.71240234375,
-0.630859375,
-0.275146484375,
-0.5673828125,
-0.61962... | 24 |
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
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)
```
| 26,678 | [
0.357177734375,
-0.09136962890625,
0.25732421875,
0.08880615234375,
-0.156494140625,
-0.634765625,
-0.34814453125,
-0.10284423828125,
-0.39306640625,
0.84423828125,
1.10546875,
-0.27685546875,
-0.03118896484375,
-0.71240234375,
-0.630859375,
-0.275146484375,
-0.5673828125,
-0.61962... | 24 |
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
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)
```
| 26,679 | [
0.357177734375,
-0.09136962890625,
0.25732421875,
0.08880615234375,
-0.156494140625,
-0.634765625,
-0.34814453125,
-0.10284423828125,
-0.39306640625,
0.84423828125,
1.10546875,
-0.27685546875,
-0.03118896484375,
-0.71240234375,
-0.630859375,
-0.275146484375,
-0.5673828125,
-0.61962... | 24 |
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
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)
```
| 26,680 | [
0.357177734375,
-0.09136962890625,
0.25732421875,
0.08880615234375,
-0.156494140625,
-0.634765625,
-0.34814453125,
-0.10284423828125,
-0.39306640625,
0.84423828125,
1.10546875,
-0.27685546875,
-0.03118896484375,
-0.71240234375,
-0.630859375,
-0.275146484375,
-0.5673828125,
-0.61962... | 24 |
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)
```
Yes
| 26,681 | [
0.439453125,
-0.0092926025390625,
0.218994140625,
0.036407470703125,
-0.2861328125,
-0.51953125,
-0.39794921875,
-0.00067138671875,
-0.37060546875,
0.81494140625,
0.98828125,
-0.215576171875,
-0.0262298583984375,
-0.669921875,
-0.59326171875,
-0.3232421875,
-0.57177734375,
-0.56591... | 24 |
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()
```
Yes
| 26,682 | [
0.439453125,
-0.0092926025390625,
0.218994140625,
0.036407470703125,
-0.2861328125,
-0.51953125,
-0.39794921875,
-0.00067138671875,
-0.37060546875,
0.81494140625,
0.98828125,
-0.215576171875,
-0.0262298583984375,
-0.669921875,
-0.59326171875,
-0.3232421875,
-0.57177734375,
-0.56591... | 24 |
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))
```
Yes
| 26,683 | [
0.439453125,
-0.0092926025390625,
0.218994140625,
0.036407470703125,
-0.2861328125,
-0.51953125,
-0.39794921875,
-0.00067138671875,
-0.37060546875,
0.81494140625,
0.98828125,
-0.215576171875,
-0.0262298583984375,
-0.669921875,
-0.59326171875,
-0.3232421875,
-0.57177734375,
-0.56591... | 24 |
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')
```
Yes
| 26,684 | [
0.439453125,
-0.0092926025390625,
0.218994140625,
0.036407470703125,
-0.2861328125,
-0.51953125,
-0.39794921875,
-0.00067138671875,
-0.37060546875,
0.81494140625,
0.98828125,
-0.215576171875,
-0.0262298583984375,
-0.669921875,
-0.59326171875,
-0.3232421875,
-0.57177734375,
-0.56591... | 24 |
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()
```
No
| 26,685 | [
0.439453125,
-0.0092926025390625,
0.218994140625,
0.036407470703125,
-0.2861328125,
-0.51953125,
-0.39794921875,
-0.00067138671875,
-0.37060546875,
0.81494140625,
0.98828125,
-0.215576171875,
-0.0262298583984375,
-0.669921875,
-0.59326171875,
-0.3232421875,
-0.57177734375,
-0.56591... | 24 |
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()
```
No
| 26,686 | [
0.439453125,
-0.0092926025390625,
0.218994140625,
0.036407470703125,
-0.2861328125,
-0.51953125,
-0.39794921875,
-0.00067138671875,
-0.37060546875,
0.81494140625,
0.98828125,
-0.215576171875,
-0.0262298583984375,
-0.669921875,
-0.59326171875,
-0.3232421875,
-0.57177734375,
-0.56591... | 24 |
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)
```
No
| 26,687 | [
0.439453125,
-0.0092926025390625,
0.218994140625,
0.036407470703125,
-0.2861328125,
-0.51953125,
-0.39794921875,
-0.00067138671875,
-0.37060546875,
0.81494140625,
0.98828125,
-0.215576171875,
-0.0262298583984375,
-0.669921875,
-0.59326171875,
-0.3232421875,
-0.57177734375,
-0.56591... | 24 |
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()
```
No
| 26,688 | [
0.439453125,
-0.0092926025390625,
0.218994140625,
0.036407470703125,
-0.2861328125,
-0.51953125,
-0.39794921875,
-0.00067138671875,
-0.37060546875,
0.81494140625,
0.98828125,
-0.215576171875,
-0.0262298583984375,
-0.669921875,
-0.59326171875,
-0.3232421875,
-0.57177734375,
-0.56591... | 24 |
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
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)))
```
| 28,729 | [
0.8671875,
0.38720703125,
0.053680419921875,
-0.1104736328125,
-0.65380859375,
-0.0654296875,
-0.476318359375,
0.406494140625,
0.1607666015625,
0.59326171875,
0.845703125,
-0.337646484375,
0.0099334716796875,
-0.465576171875,
-0.46142578125,
0.08258056640625,
-0.5458984375,
-0.8173... | 24 |
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
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))
```
| 28,730 | [
0.8671875,
0.38720703125,
0.053680419921875,
-0.1104736328125,
-0.65380859375,
-0.0654296875,
-0.476318359375,
0.406494140625,
0.1607666015625,
0.59326171875,
0.845703125,
-0.337646484375,
0.0099334716796875,
-0.465576171875,
-0.46142578125,
0.08258056640625,
-0.5458984375,
-0.8173... | 24 |
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
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="")
```
| 28,731 | [
0.8671875,
0.38720703125,
0.053680419921875,
-0.1104736328125,
-0.65380859375,
-0.0654296875,
-0.476318359375,
0.406494140625,
0.1607666015625,
0.59326171875,
0.845703125,
-0.337646484375,
0.0099334716796875,
-0.465576171875,
-0.46142578125,
0.08258056640625,
-0.5458984375,
-0.8173... | 24 |
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
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))
```
| 28,732 | [
0.8671875,
0.38720703125,
0.053680419921875,
-0.1104736328125,
-0.65380859375,
-0.0654296875,
-0.476318359375,
0.406494140625,
0.1607666015625,
0.59326171875,
0.845703125,
-0.337646484375,
0.0099334716796875,
-0.465576171875,
-0.46142578125,
0.08258056640625,
-0.5458984375,
-0.8173... | 24 |
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
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)
```
| 28,733 | [
0.8671875,
0.38720703125,
0.053680419921875,
-0.1104736328125,
-0.65380859375,
-0.0654296875,
-0.476318359375,
0.406494140625,
0.1607666015625,
0.59326171875,
0.845703125,
-0.337646484375,
0.0099334716796875,
-0.465576171875,
-0.46142578125,
0.08258056640625,
-0.5458984375,
-0.8173... | 24 |
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
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)
```
| 28,734 | [
0.8671875,
0.38720703125,
0.053680419921875,
-0.1104736328125,
-0.65380859375,
-0.0654296875,
-0.476318359375,
0.406494140625,
0.1607666015625,
0.59326171875,
0.845703125,
-0.337646484375,
0.0099334716796875,
-0.465576171875,
-0.46142578125,
0.08258056640625,
-0.5458984375,
-0.8173... | 24 |
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
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)
```
| 28,735 | [
0.8671875,
0.38720703125,
0.053680419921875,
-0.1104736328125,
-0.65380859375,
-0.0654296875,
-0.476318359375,
0.406494140625,
0.1607666015625,
0.59326171875,
0.845703125,
-0.337646484375,
0.0099334716796875,
-0.465576171875,
-0.46142578125,
0.08258056640625,
-0.5458984375,
-0.8173... | 24 |
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
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=" ")
```
| 28,736 | [
0.8671875,
0.38720703125,
0.053680419921875,
-0.1104736328125,
-0.65380859375,
-0.0654296875,
-0.476318359375,
0.406494140625,
0.1607666015625,
0.59326171875,
0.845703125,
-0.337646484375,
0.0099334716796875,
-0.465576171875,
-0.46142578125,
0.08258056640625,
-0.5458984375,
-0.8173... | 24 |
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=" ")
```
Yes
| 28,737 | [
0.8544921875,
0.3466796875,
0.06884765625,
-0.119873046875,
-0.6826171875,
0.006755828857421875,
-0.48974609375,
0.453857421875,
0.1488037109375,
0.6923828125,
0.82861328125,
-0.2337646484375,
-0.01500701904296875,
-0.410888671875,
-0.447509765625,
0.130126953125,
-0.45556640625,
-... | 24 |
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=" ")
```
Yes
| 28,738 | [
0.8544921875,
0.3466796875,
0.06884765625,
-0.119873046875,
-0.6826171875,
0.006755828857421875,
-0.48974609375,
0.453857421875,
0.1488037109375,
0.6923828125,
0.82861328125,
-0.2337646484375,
-0.01500701904296875,
-0.410888671875,
-0.447509765625,
0.130126953125,
-0.45556640625,
-... | 24 |
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=" ")
```
Yes
| 28,739 | [
0.8544921875,
0.3466796875,
0.06884765625,
-0.119873046875,
-0.6826171875,
0.006755828857421875,
-0.48974609375,
0.453857421875,
0.1488037109375,
0.6923828125,
0.82861328125,
-0.2337646484375,
-0.01500701904296875,
-0.410888671875,
-0.447509765625,
0.130126953125,
-0.45556640625,
-... | 24 |
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)))
```
Yes
| 28,740 | [
0.8544921875,
0.3466796875,
0.06884765625,
-0.119873046875,
-0.6826171875,
0.006755828857421875,
-0.48974609375,
0.453857421875,
0.1488037109375,
0.6923828125,
0.82861328125,
-0.2337646484375,
-0.01500701904296875,
-0.410888671875,
-0.447509765625,
0.130126953125,
-0.45556640625,
-... | 24 |
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)
```
No
| 28,741 | [
0.8544921875,
0.3466796875,
0.06884765625,
-0.119873046875,
-0.6826171875,
0.006755828857421875,
-0.48974609375,
0.453857421875,
0.1488037109375,
0.6923828125,
0.82861328125,
-0.2337646484375,
-0.01500701904296875,
-0.410888671875,
-0.447509765625,
0.130126953125,
-0.45556640625,
-... | 24 |
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)
```
No
| 28,742 | [
0.8544921875,
0.3466796875,
0.06884765625,
-0.119873046875,
-0.6826171875,
0.006755828857421875,
-0.48974609375,
0.453857421875,
0.1488037109375,
0.6923828125,
0.82861328125,
-0.2337646484375,
-0.01500701904296875,
-0.410888671875,
-0.447509765625,
0.130126953125,
-0.45556640625,
-... | 24 |
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)))
```
No
| 28,743 | [
0.8544921875,
0.3466796875,
0.06884765625,
-0.119873046875,
-0.6826171875,
0.006755828857421875,
-0.48974609375,
0.453857421875,
0.1488037109375,
0.6923828125,
0.82861328125,
-0.2337646484375,
-0.01500701904296875,
-0.410888671875,
-0.447509765625,
0.130126953125,
-0.45556640625,
-... | 24 |
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)
```
No
| 28,744 | [
0.8544921875,
0.3466796875,
0.06884765625,
-0.119873046875,
-0.6826171875,
0.006755828857421875,
-0.48974609375,
0.453857421875,
0.1488037109375,
0.6923828125,
0.82861328125,
-0.2337646484375,
-0.01500701904296875,
-0.410888671875,
-0.447509765625,
0.130126953125,
-0.45556640625,
-... | 24 |
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.
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)
```
| 29,389 | [
0.6328125,
0.0026874542236328125,
0.248046875,
0.495849609375,
-0.72607421875,
-0.2264404296875,
-0.07135009765625,
0.1842041015625,
0.70703125,
0.4970703125,
0.9140625,
-0.2529296875,
-0.0267486572265625,
-0.246826171875,
-0.2293701171875,
0.413330078125,
-0.427490234375,
-0.87011... | 24 |
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.
Tags: brute force, dp
Correct Solution:
```
n, a,b,c = map(int, input().split())
z = [0] + [-999999] * 50000
for i in range(1,n+1):
z[i] = max(z[i-a],z[i-b],z[i-c]) + 1
print(z[n])
```
| 29,390 | [
0.6005859375,
-0.023193359375,
0.220947265625,
0.471435546875,
-0.71044921875,
-0.21142578125,
-0.0919189453125,
0.1729736328125,
0.705078125,
0.49609375,
0.90625,
-0.204833984375,
-0.0267486572265625,
-0.2451171875,
-0.2093505859375,
0.416259765625,
-0.413330078125,
-0.85009765625... | 24 |
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.
Tags: brute force, dp
Correct Solution:
```
import sys
import math
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
from functools import reduce
sys.setrecursionlimit(10**6)
def inputt():
return sys.stdin.readline().strip()
def printt(n):
sys.stdout.write(str(n)+'\n')
def listt():
return [int(i) for i in inputt().split()]
def gcd(a,b):
return math.gcd(a,b)
def lcm(a,b):
return (a*b) // gcd(a,b)
def factors(n):
step = 2 if n%2 else 1
return set(reduce(list.__add__,([i, n//i] for i in range(1, int(math.sqrt(n))+1, step) if n % i == 0)))
def comb(n,k):
factn=math.factorial(n)
factk=math.factorial(k)
fact=math.factorial(n-k)
ans=factn//(factk*fact)
return ans
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n > 2 and n % 2 == 0:
return False
max_div = math.floor(math.sqrt(n))
for i in range(3, 1 + max_div, 2):
if n % i == 0:
return False
return True
def maxpower(n,x):
B_max = int(math.log(n, x)) + 1#tells upto what power of x n is less than it like 1024->5^4
return B_max
s = input().split()
n = int(s[0])
a = int(s[1])
b = int(s[2])
c = int(s[3])
dp = [-4001 for i in range(4000+1)]
dp[a] = 1
dp[b] = 1
dp[c] = 1
for i in range(n+1):
if i-a >= 0:
dp[i] = max(dp[i],1+dp[i-a])
if i-b >= 0:
dp[i] = max(dp[i],1+dp[i-b])
if i-c >= 0:
dp[i] = max(dp[i],1+dp[i-c])
print(dp[n])
```
| 29,391 | [
0.5146484375,
-0.024566650390625,
0.2210693359375,
0.4697265625,
-0.6455078125,
-0.027099609375,
-0.07989501953125,
0.043670654296875,
0.70751953125,
0.51513671875,
0.83642578125,
-0.40576171875,
-0.1092529296875,
-0.2427978515625,
-0.2459716796875,
0.42822265625,
-0.6181640625,
-0... | 24 |
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.
Tags: brute force, dp
Correct Solution:
```
n, a, b, c = map(int, input().split())
tmp = [a, b, c]
tmp.sort()
tmp.reverse()
a, b, c = tmp
ans = 0
for x in range(n // a + 1):
for y in range(n // b + 1):
k = n - a * x - b * y
if k < 0 or k % c != 0:
continue
z = k // c
ans = max(ans, x + y + z)
print(ans)
```
| 29,392 | [
0.572265625,
-0.03155517578125,
0.1956787109375,
0.4677734375,
-0.716796875,
-0.2017822265625,
-0.11279296875,
0.2100830078125,
0.6904296875,
0.54443359375,
0.89208984375,
-0.2430419921875,
-0.015350341796875,
-0.239501953125,
-0.22314453125,
0.431640625,
-0.43212890625,
-0.9462890... | 24 |
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.
Tags: brute force, dp
Correct Solution:
```
n,a,b,c=[int(x) for x in input().split()]
x,y,z=sorted([a,b,c])
L=[]
for i in range(n//z+1):
if i==n/z:
L.append(int(i))
break
else:
for j in range((n-i*z)//y+1):
if j==(n-i*z)/y:
L.append(int(i+j))
break
else:
t=(n-i*z-j*y)/x
if t==int(t):
L.append(int(i+j+t))
break
print(max(L))
```
| 29,393 | [
0.55078125,
-0.00412750244140625,
0.2386474609375,
0.465087890625,
-0.70361328125,
-0.2265625,
-0.0426025390625,
0.1923828125,
0.716796875,
0.5126953125,
0.8515625,
-0.2288818359375,
-0.033935546875,
-0.3076171875,
-0.237548828125,
0.38671875,
-0.4814453125,
-0.94873046875,
-0.62... | 24 |
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.
Tags: brute force, dp
Correct Solution:
```
N,a,b,c = map(int,input().split())
dp = [[0]+[-1e9 for x in range(4002)] for x in range(4)]
def max_ribbon(W, val, n):
# Build table K[][] in bottom up manner
for i in range(1,n + 1):
for w in range(1,W + 1):
if val[i-1] <= w:
dp[i][w] = max(dp[i-1][w], 1 + dp[i][w-val[i-1]])
else:
dp[i][w] = dp[i-1][w]
return dp[n][W]
val = [a,b,c]
print(max_ribbon(N,val,3))
```
| 29,394 | [
0.51025390625,
-0.03887939453125,
0.28564453125,
0.5703125,
-0.6904296875,
-0.204833984375,
-0.07232666015625,
0.1436767578125,
0.68701171875,
0.50634765625,
0.83154296875,
-0.2421875,
-0.0051116943359375,
-0.1749267578125,
-0.252685546875,
0.470703125,
-0.47705078125,
-0.844238281... | 24 |
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.
Tags: brute force, dp
Correct Solution:
```
inp=list(map(int,input().split()))
n=inp[0]
arr=inp[1:]
t=[[0 for i in range(n+1)] for i in range(4)]
for j in range(n+1):
t[0][j]=float("-inf")
for i in range(1,4):
for j in range(1,n+1):
if(arr[i-1]<=j):
t[i][j]=max(1+t[i][j-arr[i-1]],t[i-1][j])
else:
t[i][j]=t[i-1][j]
print(t[3][n])
```
| 29,395 | [
0.5654296875,
0.006610870361328125,
0.1534423828125,
0.43310546875,
-0.67529296875,
-0.1966552734375,
-0.04248046875,
0.1856689453125,
0.73291015625,
0.5,
0.9248046875,
-0.1739501953125,
0.0189666748046875,
-0.31201171875,
-0.2314453125,
0.40625,
-0.4619140625,
-0.86669921875,
-0... | 24 |
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.
Tags: brute force, dp
Correct Solution:
```
n, a, b, c = map(int, input().split())
arr = [0] + [int(-1e7)] * 4200
for i in range(1, n + 1):
arr[i] = max(arr[i - a], arr[i - b], arr[i - c]) + 1
print(arr[n])
```
| 29,396 | [
0.6064453125,
-0.0182952880859375,
0.20361328125,
0.4755859375,
-0.70947265625,
-0.2178955078125,
-0.08489990234375,
0.1793212890625,
0.71337890625,
0.47705078125,
0.93115234375,
-0.2279052734375,
-0.04376220703125,
-0.2425537109375,
-0.21630859375,
0.416015625,
-0.422119140625,
-0... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
l=list(map(int,input().split()))
n=l[0]
l.pop(0)
l.sort(reverse=True)
a,b,c=l[0],l[1],l[2]
x=0
t=0
for i in range(n//a+1):
for j in range((n-i*a)//b+1):
t=n-i*a-j*b
if t%c==0:
x=max(x,i+j+t//c)
break
print(x)
```
Yes
| 29,397 | [
0.6259765625,
0.0576171875,
0.130859375,
0.422607421875,
-0.75927734375,
-0.0731201171875,
-0.0997314453125,
0.31494140625,
0.61083984375,
0.50634765625,
0.80078125,
-0.222900390625,
-0.03558349609375,
-0.2939453125,
-0.258056640625,
0.369873046875,
-0.451416015625,
-0.8828125,
-... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000)
n, a, b, c = [int(x) for x in sys.stdin.readline().strip().split()]
dp = [0]*(4002)
dp[-1] = -10**8
for i in range(1,n+1):
dp[i] = max(dp[i-a if i-a>=0 else -1]+1,dp[i-b if i-b>=0 else -1]+1,dp[i-c if i-c>=0 else -1]+1)
print(dp[n])
```
Yes
| 29,398 | [
0.61865234375,
0.0246734619140625,
0.2337646484375,
0.4638671875,
-0.72314453125,
-0.07135009765625,
-0.08880615234375,
0.1727294921875,
0.59912109375,
0.485107421875,
0.791015625,
-0.2626953125,
-0.0511474609375,
-0.206298828125,
-0.258544921875,
0.3857421875,
-0.479248046875,
-0.... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
def Main():
n, a, b, c = map(int, input().split())
dp = [0] * 4001
dp[a] = 1
dp[b] = 1
dp[c] = 1
for i in range(n+1):
if i - a >= 0 and dp[i-a] > 0 and dp[i-a]+1 > dp[i]:
dp[i] = dp[i-a]+1
if i - b >= 0 and dp[i-b] > 0 and dp[i-b]+1 > dp[i]:
dp[i] = dp[i-b]+1
if i - c >= 0 and dp[i-c] > 0 and dp[i-c]+1 > dp[i]:
dp[i] = dp[i-c]+1
print(dp[n])
if __name__ == "__main__":
Main()
```
Yes
| 29,399 | [
0.59423828125,
0.00036454200744628906,
0.204833984375,
0.423095703125,
-0.685546875,
-0.10479736328125,
-0.09197998046875,
0.2366943359375,
0.60693359375,
0.465576171875,
0.80224609375,
-0.265869140625,
-0.021636962890625,
-0.19873046875,
-0.260009765625,
0.355712890625,
-0.490478515... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n,a,b,c=map(int,input().split())
dp=[-10000000000000]*(n+1)
dp[0]=0
for j in [a,b,c]:
for i in range(j,n+1):
dp[i]=max(dp[i],dp[i-j]+1)
print(dp[n])
```
Yes
| 29,400 | [
0.64990234375,
0.03167724609375,
0.15576171875,
0.453369140625,
-0.7578125,
-0.1019287109375,
-0.09954833984375,
0.26025390625,
0.60888671875,
0.471923828125,
0.82568359375,
-0.250244140625,
-0.056060791015625,
-0.2420654296875,
-0.245849609375,
0.3583984375,
-0.4150390625,
-0.8208... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
import sys
n, s1, s2, s3 = list(map(int, input().split()))
a = min(s1, s2, s3)
c = max(s1, s2, s3)
b = s1 + s2 + s3 - a - c
r = n % a
f = []
if r == 0:
print(n//a)
else:
for i in range(1, n//a+1):
nn = a*i + r
nr = nn % b
if nr == 0:
print(n // a - i , nn // b)
sys.exit()
for j in range(0, nn//b):
nnn = a*i + r - j * b
nnr = nnn % c
if nnr == 0:
ta = n // a - i
tc = nnn // c
tb = (n - ta * a - tc*c) // b
print(ta, tb , tc)
sys.exit()
```
No
| 29,401 | [
0.62646484375,
0.0989990234375,
0.1634521484375,
0.38818359375,
-0.76171875,
-0.07659912109375,
-0.080810546875,
0.2210693359375,
0.5810546875,
0.467529296875,
0.82177734375,
-0.2359619140625,
-0.010040283203125,
-0.3017578125,
-0.2470703125,
0.384033203125,
-0.43505859375,
-0.8554... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n,a,b,c=[int(x) for x in input().split()]
m=0
q=max(a,b,c)
w=min(a,b,c)
e=a+b+c-q-w
c=w;b=e;a=q
ws=0
if n==3999:print(1)
elif n==490 and c==4:print(111)
else :
for i in range(n//a+1):
for j in range(n//b+1):
for k in range(n//c+1):
if i*a+j*b+(n//c-k)*c==n:
m=n//c+i+j-k
ws=1
break
if ws:break
if ws:break
print(m)
```
No
| 29,402 | [
0.59375,
0.060882568359375,
0.1358642578125,
0.44384765625,
-0.77783203125,
-0.07147216796875,
-0.058441162109375,
0.27685546875,
0.5888671875,
0.50048828125,
0.810546875,
-0.239501953125,
-0.06982421875,
-0.35009765625,
-0.250244140625,
0.385986328125,
-0.548828125,
-0.87060546875... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n,a,b,c=map(int,input().split())
lst=[a,b,c]
lst.sort()
m=[]
if n==a or n==b or n==c:
m.append(1)
if a+b==n or a+c==n or b+c==n:
m.append(2)
if a+b+c==n:
m.append(3)
if n%lst[0]==0:
m.append((n/lst[0]))
if n%lst[1]==0:
m.append((n/lst[1]))
if n%lst[2]==0:
m.append((n/lst[2]))
if n%lst[0]!=0:
c=n-int(n/lst[0])*lst[0]
if c==lst[1]:
m.append((n//lst[0]+1))
elif c%lst[1]==0:
m.append((n//lst[0]+c//lst[1]))
else:
c1=c-int(n/lst[1])*lst[1]
if c1==lst[2]:
m.append((n//lst[0]+c//lst[1]+1))
elif c1%lst[2]==0:
m.append((n//lst[0]+c//lst[1]+c1//lst[2]))
if c==lst[2]:
m.append((n//lst[0]+1))
elif c%lst[2]==0:
m.append((n//lst[0]+c//lst[2]))
else:
c1=c-int(n/lst[2])*lst[2]
if c1==lst[1]:
m.append((n//lst[0]+c//lst[2]+1))
elif c1%lst[1]==0:
m.append((n//lst[0]+c//lst[2]+c1//lst[1]))
if n%lst[1]!=0:
c=n-int(n/lst[1])*lst[1]
if c==lst[0]:
m.append((n//lst[1]+1))
elif c%lst[0]==0:
m.append((n//lst[1]+c//lst[0]))
else:
c1=c-int(n/lst[0])*lst[0]
if c1==lst[2]:
m.append((n//lst[1]+c//lst[0]+1))
elif c1%lst[2]==0:
m.append((n//lst[1]+c//lst[0]+c1//lst[2]))
if c==lst[2]:
m.append((n//lst[1]+1))
elif c%lst[2]==0:
m.append((n//lst[1]+c//lst[2]))
else:
c1=c-int(n/lst[2])*lst[2]
if c1==lst[0]:
m.append((n//lst[1]+c//lst[2]+1))
elif c1%lst[0]==0:
m.append((n//lst[1]+c//lst[2]+c1//lst[0]))
if n%lst[2]!=0:
c=n-int(n/lst[2])*lst[2]
if c==lst[0]:
m.append((n//lst[2]+1))
elif c%lst[0]==0:
m.append((n//lst[2]+c//lst[0]))
else:
c1=c-int(n/lst[0])*lst[0]
if c1==lst[1]:
m.append((n//lst[2]+c//lst[0]+1))
elif c1%lst[1]==0:
m.append((n//lst[2]+c//lst[0]+c1//lst[1]))
if c==lst[1]:
m.append((n//lst[2]+1))
elif c%lst[1]==0:
m.append((n//lst[2]+c//lst[1]))
else:
c1=c-int(n/lst[1])*lst[1]
if c1==lst[0]:
m.append((n//lst[2]+c//lst[1]+1))
elif c1%lst[0]==0:
m.append((n//lst[2]+c//lst[1]+c1//lst[0]))
if n==4000 and a==3 and b==4:
print(1333)
else:
print(int(max(m)))
```
No
| 29,403 | [
0.64892578125,
0.0802001953125,
0.2041015625,
0.364990234375,
-0.73681640625,
-0.0721435546875,
-0.0806884765625,
0.327880859375,
0.57861328125,
0.485595703125,
0.79833984375,
-0.26416015625,
-0.01137542724609375,
-0.293701171875,
-0.25927734375,
0.34521484375,
-0.494384765625,
-0.... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
if __name__ == '__main__':
n, a, b, c = [int(x) for x in input().split()]
dp = [0] * (n+1)
for i in range(1, n + 1):
x, y, z = -1, -1, -1
if x == -1 and y == -1 and z == -1:
dp[i] = -1
else:
dp[i] = max(max(y, z), x) + 1
if i >= a:
x = dp[i - a]
if i >= b:
y = dp[i - b]
if i >= c:
z = dp[i - c]
print(dp[n])
```
No
| 29,404 | [
0.61767578125,
-0.0030803680419921875,
0.2308349609375,
0.43798828125,
-0.7119140625,
-0.09405517578125,
-0.068603515625,
0.24267578125,
0.6044921875,
0.51123046875,
0.85986328125,
-0.2239990234375,
-0.016510009765625,
-0.26025390625,
-0.26416015625,
0.350341796875,
-0.490478515625,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of n computers and m cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with n nodes and m edges. Let's index the computers with integers from 1 to n, let's index the cables with integers from 1 to m.
Polycarpus was given an important task — check the reliability of his company's network. For that Polycarpus decided to carry out a series of k experiments on the computer network, where the i-th experiment goes as follows:
1. Temporarily disconnect the cables with indexes from li to ri, inclusive (the other cables remain connected).
2. Count the number of connected components in the graph that is defining the computer network at that moment.
3. Re-connect the disconnected cables with indexes from li to ri (that is, restore the initial network).
Help Polycarpus carry out all experiments and for each print the number of connected components in the graph that defines the computer network through the given experiment. Isolated vertex should be counted as single component.
Input
The first line contains two space-separated integers n, m (2 ≤ n ≤ 500; 1 ≤ m ≤ 104) — the number of computers and the number of cables, correspondingly.
The following m lines contain the cables' description. The i-th line contains space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the numbers of the computers that are connected by the i-th cable. Note that a pair of computers can be connected by multiple cables.
The next line contains integer k (1 ≤ k ≤ 2·104) — the number of experiments. Next k lines contain the experiments' descriptions. The i-th line contains space-separated integers li, ri (1 ≤ li ≤ ri ≤ m) — the numbers of the cables that Polycarpus disconnects during the i-th experiment.
Output
Print k numbers, the i-th number represents the number of connected components of the graph that defines the computer network during the i-th experiment.
Examples
Input
6 5
1 2
5 4
2 3
3 1
3 6
6
1 3
2 5
1 5
5 5
2 4
3 3
Output
4
5
6
3
4
2
Submitted Solution:
```
def dsearch(start_point, used_nodes, cycle, matrix):
used_nodes[start_point] = False
connected = matrix[start_point]
for index, node in enumerate(connected):
if node and used_nodes[index]:
used_nodes[index] = False
cycle.append(index)
dsearch(index, used_nodes, cycle, matrix)
n, m = (int(x) for x in input().split())
matrix = [[0] * n for i in range(n)]
used_nodes = [True for i in range(n)]
cycles = []
for i in range(m):
a, b = (int(x) - 1 for x in input().split())
matrix[b][a] = 1
matrix[a][b] = 1
for index, node in enumerate(used_nodes):
if node:
cycle = [index]
dsearch(index, used_nodes, cycle, matrix)
cycles.append(cycle)
print(len(cycles))
for c in cycles:
print(len(c))
for i in c:
print(i + 1, end=' ')
print()
```
No
| 30,386 | [
0.20849609375,
0.18994140625,
0.2222900390625,
0.313232421875,
-0.301513671875,
-0.2471923828125,
-0.388916015625,
-0.0784912109375,
0.46630859375,
0.70849609375,
0.76904296875,
0.01052093505859375,
0.166259765625,
-0.74267578125,
-0.48388671875,
0.0268096923828125,
-0.689453125,
-... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Tags: greedy, two pointers
Correct Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
[p,count,sim] = [1,0,0]
is_solution_there=False
for i in range(1,n+1):
while p<i and a[i] - t + 1>a[p]:
p+=1
if b[p]!=b[p-1]:
sim = max(sim-1,0)
if a[i]<a[p]+t and sim<m:
count+=1
sim+=1
if sim==m:
is_solution_there=True
b[i] = count
if is_solution_there==False:
print("No solution")
return
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
```
| 31,358 | [
0.039764404296875,
0.343994140625,
-0.059661865234375,
0.409912109375,
-0.2220458984375,
-0.46630859375,
-0.4921875,
-0.070556640625,
0.806640625,
0.68359375,
0.488037109375,
-0.2099609375,
0.39111328125,
-0.61083984375,
-0.68212890625,
0.1378173828125,
-0.7939453125,
-0.4167480468... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Tags: greedy, two pointers
Correct Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
[a,b]=[[0]*20002,[0]*20002]
if n<m:
print("No solution")
return
for i in range(1,n+1):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
[p,count,sim,ist] = [1,0,0,False]
for i in range(1,n+1):
while p<i and a[i] - t + 1>a[p]:
p+=1
if b[p]!=b[p-1]:
sim = max(sim-1,0)
if a[i]<a[p]+t and sim<m:
[count,sim] = [count+1,sim+1]
if sim==m:
ist=True
b[i] = count
if ist==False:
print("No solution")
return
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
```
| 31,359 | [
0.039764404296875,
0.343994140625,
-0.059661865234375,
0.409912109375,
-0.2220458984375,
-0.46630859375,
-0.4921875,
-0.070556640625,
0.806640625,
0.68359375,
0.488037109375,
-0.2099609375,
0.39111328125,
-0.61083984375,
-0.68212890625,
0.1378173828125,
-0.7939453125,
-0.4167480468... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
[p,count,sim] = [1,0,0]
is_solution_there=False
for i in range(1,n+1):
while p<i and a[i] - t + 1>a[p]:
p+=1
if b[p]!=b[p-1]:
sim = max(sim-1,1)
if a[i]<a[p]+t and sim<m:
count+=1
sim+=1
if sim==m:
is_solution_there=True
b[i] = count
if is_solution_there==False:
print("No solution")
return
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
```
No
| 31,360 | [
0.1087646484375,
0.4248046875,
-0.0576171875,
0.423583984375,
-0.1578369140625,
-0.35693359375,
-0.5224609375,
0.02606201171875,
0.77880859375,
0.67578125,
0.413330078125,
-0.2147216796875,
0.378662109375,
-0.62744140625,
-0.7705078125,
0.08795166015625,
-0.83251953125,
-0.42016601... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(n):
g = gets()
temp = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
a[i] = temp
[p,count,k,sim] = [0,0,0,0]
for i in range(n):
while p<i and a[i] - t + 1>=a[p]:
p+=1
sim = min(sim,m,i-p+1)
#print(p,a[p],a[i],a[i] - a[p],sim,i-p)
if p==i or (a[i] - t +1<a[p] and sim<m):
count+=1
b[k] = count
sim+=1
else:
b[k] = count
k+=1
print(count)
for i in range(20002):
if b[i] == 0:
break
print(b[i])
if mode=="file":f.close()
if __name__=="__main__":
main()
```
No
| 31,361 | [
0.1087646484375,
0.4248046875,
-0.0576171875,
0.423583984375,
-0.1578369140625,
-0.35693359375,
-0.5224609375,
0.02606201171875,
0.77880859375,
0.67578125,
0.413330078125,
-0.2147216796875,
0.378662109375,
-0.62744140625,
-0.7705078125,
0.08795166015625,
-0.83251953125,
-0.42016601... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
temp = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
a[i] = temp
#print(a[i])
[p,count,sim] = [1,0,0]
for i in range(1,n+1):
while p<i and a[i] - t + 1>=a[p]:
p+=1
#print("Dec",end=' ')
if b[p]!=b[p-1]:
#print("yes")
sim = max(sim-1,0)
#print(p,a[p],a[i],a[i] - a[p],sim,i-p)
if a[i] not in [82126,13978] and (i==p or (a[i] - t +1<a[p] and sim<m)):
count+=1
b[i] = count
sim+=1
else:
b[i] = count
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
```
No
| 31,362 | [
0.1087646484375,
0.4248046875,
-0.0576171875,
0.423583984375,
-0.1578369140625,
-0.35693359375,
-0.5224609375,
0.02606201171875,
0.77880859375,
0.67578125,
0.413330078125,
-0.2147216796875,
0.378662109375,
-0.62744140625,
-0.7705078125,
0.08795166015625,
-0.83251953125,
-0.42016601... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
* the number of different users online did not exceed M at any moment,
* at some second the number of distinct users online reached value M,
* the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
Input
The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).
Output
In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).
Examples
Input
4 2 10
17:05:53
17:05:58
17:06:01
22:39:47
Output
3
1
2
2
3
Input
1 2 86400
00:00:00
Output
No solution
Note
Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.
In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
[n,m,t]=get()
a=[0]*20002
b=[0]*20002
if n<m:
print("No solution")
return
for i in range(1,1+n):
g = gets()
a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
#print(a[i])
[p,count,sim] = [1,0,0]
for i in range(1,n+1):
while p<i and a[i] - t + 1>=a[p]:
p+=1
if b[p]!=b[p-1]:
#print("yes")
sim = max(sim-1,0)
#print(p,a[p],a[i],a[i] - a[p],sim,i-p)
if a[i]<a[p]+t and sim<m:
count+=1
sim+=1
b[i] = count
print(count)
for i in range(1,n+1):
print(b[i],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
```
No
| 31,363 | [
0.1087646484375,
0.4248046875,
-0.0576171875,
0.423583984375,
-0.1578369140625,
-0.35693359375,
-0.5224609375,
0.02606201171875,
0.77880859375,
0.67578125,
0.413330078125,
-0.2147216796875,
0.378662109375,
-0.62744140625,
-0.7705078125,
0.08795166015625,
-0.83251953125,
-0.42016601... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Tags: data structures
Correct 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, deque
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)
mod = 998244353
INF = float('inf')
class BIT:
def __init__(self, n):
self.btree = [0]*(n+1)
self.n = n
def lowbit(self, num):
return num & (-num)
def update(self, ind, val):
while ind<self.n+1:
self.btree[ind]+=val
ind+=self.lowbit(ind)
def sum(self, ind):
res = 0
while ind:
res+=self.btree[ind]
ind-=self.lowbit(ind)
return res
# ------------------------------
def main():
n, m = RL()
arr = RLL()
bt = BIT(n+m)
mi = [i for i in range(n+1)]
ma = [i for i in range(n+1)]
for i in range(1, n+1):
bt.update(m+i, 1)
rec = [i+m for i in range(n+1)]
pos = m
for q in arr:
mi[q] = 1
ma[q] = max(ma[q], bt.sum(rec[q]))
bt.update(pos, 1)
bt.update(rec[q], -1)
rec[q] = pos
pos-=1
for i in range(1, n+1):
ma[i] = max(ma[i], bt.sum(rec[i]))
for i in range(1, n+1):
print(mi[i], ma[i])
if __name__ == "__main__":
main()
```
| 31,868 | [
0.54150390625,
-0.06524658203125,
0.138427734375,
0.5810546875,
-0.24462890625,
-0.9365234375,
-0.421630859375,
0.36962890625,
0.10748291015625,
0.71337890625,
1.1240234375,
-0.177490234375,
0.18505859375,
-0.62939453125,
-0.8720703125,
0.213623046875,
-0.7841796875,
-0.6953125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Tags: data structures
Correct Solution:
```
import io
import os
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, messages):
# Initial mn/mx is their initial positions
ans = [[i, i] for i in range(N)]
friendsList = SortedList()
friendsToTime = {i: i for i in range(N)}
for f, t in friendsToTime.items():
friendsList.add((t, f))
for t, f in enumerate(messages):
index = friendsList.bisect_left((friendsToTime[f], f))
ans[f][1] = max(ans[f][1], index)
friendsList.remove((friendsToTime[f], f))
friendsToTime[f] = -t - 1
friendsList.add((friendsToTime[f], f))
ans[f][0] = min(ans[f][0], 0)
for i, (t, f) in enumerate(friendsList):
ans[f][0] = min(ans[f][0], i)
ans[f][1] = max(ans[f][1], i)
return "\n".join(str(x + 1) + " " + str(y + 1) for x, y in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
messages = [int(x) - 1 for x in input().split()] # 0 indexed
ans = solve(N, M, messages)
print(ans)
```
| 31,869 | [
0.54150390625,
-0.06524658203125,
0.138427734375,
0.5810546875,
-0.24462890625,
-0.9365234375,
-0.421630859375,
0.36962890625,
0.10748291015625,
0.71337890625,
1.1240234375,
-0.177490234375,
0.18505859375,
-0.62939453125,
-0.8720703125,
0.213623046875,
-0.7841796875,
-0.6953125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Tags: data structures
Correct Solution:
```
n, m = map(int, input().split())
a = [int(i) - 1 for i in input().split()]
ans1 = [i + 1 for i in range(n)]
ans2 = [-1 for i in range(n)]
for i in set(a):
ans1[i] = 1
N = 1
while N < n + m: N <<= 1
st = [0 for i in range(N << 1)]
pos = [i + m for i in range(n)]
for i in range(n):
st[i + N + m] = 1
for i in range(N - 1, 0, -1):
st[i] = st[i << 1] + st[i << 1 | 1]
def up(i,v):
i+=N
st[i]=v
i>>=1
while(i>0):
st[i]=st[i<<1]+st[i<<1|1]
i>>=1
def qr(l,r=N):
l+=N
r+=N
add=0
while(l<r):
if l&1:
add+=st[l]
l+=1
if(r&1):
add+=st[r]
r-=1
l>>=1
r>>=1
return add
for j in range(m):
x = a[j]
i = pos[x]
ans2[x] = max(ans2[x], n - qr(i + 1))
up(i, 0)
pos[x] = m - 1 - j
up(pos[x], 1)
for i in range(n):
x = pos[i]
ans2[i] = max(ans2[i], n - qr(x + 1))
for i in range(n):
print(ans1[i], ans2[i])
```
| 31,870 | [
0.54150390625,
-0.06524658203125,
0.138427734375,
0.5810546875,
-0.24462890625,
-0.9365234375,
-0.421630859375,
0.36962890625,
0.10748291015625,
0.71337890625,
1.1240234375,
-0.177490234375,
0.18505859375,
-0.62939453125,
-0.8720703125,
0.213623046875,
-0.7841796875,
-0.6953125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Tags: data structures
Correct Solution:
```
import io
import os
import random
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/Treap.py
# Modified to support bisect_left/bisect_right/__getitem__ like SortedList
class TreapMultiSet(object):
root = 0
size = 0
def __init__(self, data=None):
if data:
data = sorted(data)
self.root = treap_builder(data)
self.size = len(data)
def add(self, key):
self.root = treap_insert(self.root, key)
self.size += 1
def remove(self, key):
self.root = treap_erase(self.root, key)
self.size -= 1
def discard(self, key):
try:
self.remove(key)
except KeyError:
pass
def ceiling(self, key):
x = treap_ceiling(self.root, key)
return treap_keys[x] if x else None
def higher(self, key):
x = treap_higher(self.root, key)
return treap_keys[x] if x else None
def floor(self, key):
x = treap_floor(self.root, key)
return treap_keys[x] if x else None
def lower(self, key):
x = treap_lower(self.root, key)
return treap_keys[x] if x else None
def max(self):
return treap_keys[treap_max(self.root)]
def min(self):
return treap_keys[treap_min(self.root)]
def __len__(self):
return self.size
def __nonzero__(self):
return bool(self.root)
__bool__ = __nonzero__
def __contains__(self, key):
return self.floor(key) == key
def __repr__(self):
return "TreapMultiSet({})".format(list(self))
def __iter__(self):
if not self.root:
return iter([])
out = []
stack = [self.root]
while stack:
node = stack.pop()
if node > 0:
if right_child[node]:
stack.append(right_child[node])
stack.append(~node)
if left_child[node]:
stack.append(left_child[node])
else:
out.append(treap_keys[~node])
return iter(out)
def __getitem__(self, index):
return treap_find_kth(self.root, index)
def bisect_left(self, value):
return treap_bisect_left(self.root, value)
def bisect_right(self, value):
return treap_bisect_right(self.root, value)
class TreapSet(TreapMultiSet):
def add(self, key):
self.root, duplicate = treap_insert_unique(self.root, key)
if not duplicate:
self.size += 1
def __repr__(self):
return "TreapSet({})".format(list(self))
class TreapHashSet(TreapMultiSet):
def __init__(self, data=None):
if data:
self.keys = set(data)
super(TreapHashSet, self).__init__(self.keys)
else:
self.keys = set()
def add(self, key):
if key not in self.keys:
self.keys.add(key)
super(TreapHashSet, self).add(key)
def remove(self, key):
self.keys.remove(key)
super(TreapHashSet, self).remove(key)
def discard(self, key):
if key in self.keys:
self.remove(key)
def __contains__(self, key):
return key in self.keys
def __repr__(self):
return "TreapHashSet({})".format(list(self))
class TreapHashMap(TreapMultiSet):
def __init__(self, data=None):
if data:
self.map = dict(data)
super(TreapHashMap, self).__init__(self.map.keys())
else:
self.map = dict()
def __setitem__(self, key, value):
if key not in self.map:
super(TreapHashMap, self).add(key)
self.map[key] = value
def __getitem__(self, key):
return self.map[key]
def add(self, key):
raise TypeError("add on TreapHashMap")
def get(self, key, default=None):
return self.map.get(key, default=default)
def remove(self, key):
self.map.pop(key)
super(TreapHashMap, self).remove(key)
def discard(self, key):
if key in self.map:
self.remove(key)
def __contains__(self, key):
return key in self.map
def __repr__(self):
return "TreapHashMap({})".format(list(self))
left_child = [0]
right_child = [0]
subtree_size = [0]
treap_keys = [0]
treap_prior = [0.0]
def treap_builder(sorted_data):
"""Build a treap in O(n) time using sorted data"""
def build(begin, end):
if begin == end:
return 0
mid = (begin + end) // 2
root = treap_create_node(sorted_data[mid])
left_child[root] = build(begin, mid)
right_child[root] = build(mid + 1, end)
subtree_size[root] = end - begin
# sift down the priorities
ind = root
while True:
lc = left_child[ind]
rc = right_child[ind]
if lc and treap_prior[lc] > treap_prior[ind]:
if rc and treap_prior[rc] > treap_prior[rc]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
treap_prior[ind], treap_prior[lc] = treap_prior[lc], treap_prior[ind]
ind = lc
elif rc and treap_prior[rc] > treap_prior[ind]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
break
return root
return build(0, len(sorted_data))
def treap_create_node(key):
treap_keys.append(key)
treap_prior.append(random.random())
left_child.append(0)
right_child.append(0)
subtree_size.append(1)
return len(treap_keys) - 1
def treap_split(root, key):
left_pos = right_pos = 0
stack = []
while root:
if key < treap_keys[root]:
left_child[right_pos] = right_pos = root
root = left_child[root]
stack.append(right_pos)
else:
right_child[left_pos] = left_pos = root
root = right_child[root]
stack.append(left_pos)
left, right = right_child[0], left_child[0]
right_child[left_pos] = left_child[right_pos] = right_child[0] = left_child[0] = 0
treap_update(stack)
return left, right
def treap_merge(left, right):
where, pos = left_child, 0
stack = []
while left and right:
if treap_prior[left] > treap_prior[right]:
where[pos] = pos = left
where = right_child
left = right_child[left]
else:
where[pos] = pos = right
where = left_child
right = left_child[right]
stack.append(pos)
where[pos] = left or right
node = left_child[0]
left_child[0] = 0
treap_update(stack)
return node
def treap_insert(root, key):
if not root:
return treap_create_node(key)
left, right = treap_split(root, key)
return treap_merge(treap_merge(left, treap_create_node(key)), right)
def treap_insert_unique(root, key):
if not root:
return treap_create_node(key), False
left, right = treap_split(root, key)
if left and treap_keys[left] == key:
return treap_merge(left, right), True
return treap_merge(treap_merge(left, treap_create_node(key)), right), False
def treap_erase(root, key):
if not root:
raise KeyError(key)
if treap_keys[root] == key:
return treap_merge(left_child[root], right_child[root])
node = root
stack = [root]
while root and treap_keys[root] != key:
parent = root
root = left_child[root] if key < treap_keys[root] else right_child[root]
stack.append(root)
if not root:
raise KeyError(key)
if root == left_child[parent]:
left_child[parent] = treap_merge(left_child[root], right_child[root])
else:
right_child[parent] = treap_merge(left_child[root], right_child[root])
treap_update(stack)
return node
def treap_ceiling(root, key):
while root and treap_keys[root] < key:
root = right_child[root]
if not root:
return 0
min_node = root
min_key = treap_keys[root]
while root:
if treap_keys[root] < key:
root = right_child[root]
else:
if treap_keys[root] < min_key:
min_key = treap_keys[root]
min_node = root
root = left_child[root]
return min_node
def treap_higher(root, key):
while root and treap_keys[root] <= key:
root = right_child[root]
if not root:
return 0
min_node = root
min_key = treap_keys[root]
while root:
if treap_keys[root] <= key:
root = right_child[root]
else:
if treap_keys[root] < min_key:
min_key = treap_keys[root]
min_node = root
root = left_child[root]
return min_node
def treap_floor(root, key):
while root and treap_keys[root] > key:
root = left_child[root]
if not root:
return 0
max_node = root
max_key = treap_keys[root]
while root:
if treap_keys[root] > key:
root = left_child[root]
else:
if treap_keys[root] > max_key:
max_key = treap_keys[root]
max_node = root
root = right_child[root]
return max_node
def treap_lower(root, key):
while root and treap_keys[root] >= key:
root = left_child[root]
if not root:
return 0
max_node = root
max_key = treap_keys[root]
while root:
if treap_keys[root] >= key:
root = left_child[root]
else:
if treap_keys[root] > max_key:
max_key = treap_keys[root]
max_node = root
root = right_child[root]
return max_node
def treap_min(root):
if not root:
raise ValueError("min on empty treap")
while left_child[root]:
root = left_child[root]
return root
def treap_max(root):
if not root:
raise ValueError("max on empty treap")
while right_child[root]:
root = right_child[root]
return root
def treap_update(path):
for node in reversed(path):
assert node != 0 # ensure subtree_size[nullptr] == 0
lc = left_child[node]
rc = right_child[node]
subtree_size[node] = subtree_size[lc] + 1 + subtree_size[rc]
def treap_find_kth(root, k):
if not root or not (0 <= k < subtree_size[root]):
raise IndexError("treap index out of range")
while True:
lc = left_child[root]
left_size = subtree_size[lc]
if k < left_size:
root = lc
continue
k -= left_size
if k == 0:
return treap_keys[root]
k -= 1
rc = right_child[root]
# assert k < subtree_size[rc]
root = rc
def treap_bisect_left(root, key):
index = 0
while root:
if treap_keys[root] < key:
index += subtree_size[left_child[root]] + 1
root = right_child[root]
else:
root = left_child[root]
return index
def treap_bisect_right(root, key):
index = 0
while root:
if treap_keys[root] <= key:
index += subtree_size[left_child[root]] + 1
root = right_child[root]
else:
root = left_child[root]
return index
# End treap copy and paste
def solve(N, M, messages):
# Initial mn/mx is their initial positions
ans = [[i, i] for i in range(N)]
#friendsList = SortedList()
friendsList = TreapMultiSet()
friendsToTime = {i: i for i in range(N)}
for f, t in friendsToTime.items():
friendsList.add((t, f))
for t, f in enumerate(messages):
index = friendsList.bisect_left((friendsToTime[f], f))
ans[f][1] = max(ans[f][1], index)
friendsList.remove((friendsToTime[f], f))
friendsToTime[f] = -t - 1
friendsList.add((friendsToTime[f], f))
ans[f][0] = min(ans[f][0], 0)
for i, (t, f) in enumerate(friendsList):
ans[f][0] = min(ans[f][0], i)
ans[f][1] = max(ans[f][1], i)
return "\n".join(str(x + 1) + " " + str(y + 1) for x, y in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
messages = [int(x) - 1 for x in input().split()] # 0 indexed
ans = solve(N, M, messages)
print(ans)
```
| 31,871 | [
0.54150390625,
-0.06524658203125,
0.138427734375,
0.5810546875,
-0.24462890625,
-0.9365234375,
-0.421630859375,
0.36962890625,
0.10748291015625,
0.71337890625,
1.1240234375,
-0.177490234375,
0.18505859375,
-0.62939453125,
-0.8720703125,
0.213623046875,
-0.7841796875,
-0.6953125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Tags: data structures
Correct Solution:
```
from sys import stdin, stdout
def update(bita, pos, v):
while pos < len(bita):
bita[pos] += v
pos += lowbit(pos)
def query(bita, pos):
res = 0
while pos > 0:
res += bita[pos]
pos -= lowbit(pos)
return res
def lowbit(p):
return p&(-p)
def getminmax(n, m, ma):
bita = [0]*(n+m+1)
minmax = [[0,0] for i in range(n+1)]
pos = [0]*(n+1)
for i in range(1, n+1):
update(bita, n+1-i, 1)
minmax[i][0] = i
minmax[i][1] = i
pos[i] = n+1-i
#print(bita)
#print(query(bita, n+m))
for i in range(n+1, n+1+m):
mes = ma[i-n-1]
minmax[mes][0] = 1
minmax[mes][1] = max(minmax[mes][1], n - query(bita, pos[mes]-1))
update(bita, pos[mes], -1)
pos[mes] = i
update(bita, pos[mes], 1)
#print(bita)
#print(pos)
for i in range(1, n + 1):
minmax[i][1] = max(minmax[i][1], n - query(bita, pos[i] - 1))
return minmax
if __name__ == '__main__':
nm = list(map(int, stdin.readline().split()))
n = nm[0]
m = nm[1]
ma = list(map(int, stdin.readline().split()))
minmax = getminmax(n,m, ma)
for i in range(1, n+1):
stdout.write(str(minmax[i][0]) + ' ' + str(minmax[i][1]) + '\n')
```
| 31,872 | [
0.54150390625,
-0.06524658203125,
0.138427734375,
0.5810546875,
-0.24462890625,
-0.9365234375,
-0.421630859375,
0.36962890625,
0.10748291015625,
0.71337890625,
1.1240234375,
-0.177490234375,
0.18505859375,
-0.62939453125,
-0.8720703125,
0.213623046875,
-0.7841796875,
-0.6953125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Tags: data structures
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
class FastIntregral:
def __init__(self, n, *args, **kwargs):
self.mData = [0 for i in range(n+1)]
self.mSize = n
def upd(self, index , value):
while index <= self.mSize:
self.mData[index] += value
index += index & -index
def s(self, index ):
res = 0
while index > 0:
res += self.mData[index]
index -= index & -index
return res
n , m = [int(i) for i in input().split()]
T = FastIntregral( m + n + 1 )
idx = [i + m for i in range(n+1)]
ans_min = [False for i in range(n+1)]
ans_max = [i for i in range(n+1)]
for i in range(m+1 , n + m + 2): T.upd(i,1)
for q in [int(i) for i in input().split()]:
ans_min[q] = True
ans_max[q] = max(ans_max[q] , T.s(idx[q]))
T.upd(idx[q],-1) ; T.upd(m,1)
idx[q] = m ; m -= 1
for i in range(1,n+1):
print(("1" if ans_min[i] else str(i)) + " " + str(max(ans_max[i],T.s(idx[i]))))
```
| 31,873 | [
0.54150390625,
-0.06524658203125,
0.138427734375,
0.5810546875,
-0.24462890625,
-0.9365234375,
-0.421630859375,
0.36962890625,
0.10748291015625,
0.71337890625,
1.1240234375,
-0.177490234375,
0.18505859375,
-0.62939453125,
-0.8720703125,
0.213623046875,
-0.7841796875,
-0.6953125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Tags: data structures
Correct Solution:
```
from __future__ import division, print_function
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
alphabets = list('abcdefghijklmnopqrstuvwxyz')
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def main():
n,m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
minans = [3*100000]*(n+1)
maxans = [0]*(n+1)
s = SortedList()
prev = [(1e7)]*(n+1)
cur = 1e7
for i in range(1,n+1):
s.add((cur,i))
for i in a:
minans[i]=1
element = (prev[i],i)
pos = s.bisect_left(element)
maxans[i]=max(maxans[i],pos+1)
s.remove(element)
cur-=1
prev[i]=cur
s.add((cur,i))
for i in range(1,n+1):
element = s[i-1][1]
minans[element]=min(minans[element],i,element)
maxans[element]=max(maxans[element],i)
for i in range(1,n+1):
print(minans[i],maxans[i])
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
| 31,874 | [
0.54150390625,
-0.06524658203125,
0.138427734375,
0.5810546875,
-0.24462890625,
-0.9365234375,
-0.421630859375,
0.36962890625,
0.10748291015625,
0.71337890625,
1.1240234375,
-0.177490234375,
0.18505859375,
-0.62939453125,
-0.8720703125,
0.213623046875,
-0.7841796875,
-0.6953125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Tags: data structures
Correct Solution:
```
import io
import os
import random
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/Treap.py
# Modified to support bisect_left/bisect_right/__getitem__ like SortedList
class TreapMultiSet(object):
root = 0
size = 0
def __init__(self, data=None):
if data:
data = sorted(data)
self.root = treap_builder(data)
self.size = len(data)
def add(self, key):
self.root = treap_insert(self.root, key)
self.size += 1
def remove(self, key):
self.root = treap_erase(self.root, key)
self.size -= 1
def discard(self, key):
try:
self.remove(key)
except KeyError:
pass
def ceiling(self, key):
x = treap_ceiling(self.root, key)
return treap_keys[x] if x else None
def higher(self, key):
x = treap_higher(self.root, key)
return treap_keys[x] if x else None
def floor(self, key):
x = treap_floor(self.root, key)
return treap_keys[x] if x else None
def lower(self, key):
x = treap_lower(self.root, key)
return treap_keys[x] if x else None
def max(self):
return treap_keys[treap_max(self.root)]
def min(self):
return treap_keys[treap_min(self.root)]
def __len__(self):
return self.size
def __nonzero__(self):
return bool(self.root)
__bool__ = __nonzero__
def __contains__(self, key):
return self.floor(key) == key
def __repr__(self):
return "TreapMultiSet({})".format(list(self))
def __iter__(self):
if not self.root:
return iter([])
out = []
stack = [self.root]
while stack:
node = stack.pop()
if node > 0:
if right_child[node]:
stack.append(right_child[node])
stack.append(~node)
if left_child[node]:
stack.append(left_child[node])
else:
out.append(treap_keys[~node])
return iter(out)
def __getitem__(self, index):
return treap_find_kth(self.root, index)
def bisect_left(self, value):
return treap_bisect_left(self.root, value)
def bisect_right(self, value):
return treap_bisect_right(self.root, value)
class TreapSet(TreapMultiSet):
def add(self, key):
self.root, duplicate = treap_insert_unique(self.root, key)
if not duplicate:
self.size += 1
def __repr__(self):
return "TreapSet({})".format(list(self))
class TreapHashSet(TreapMultiSet):
def __init__(self, data=None):
if data:
self.keys = set(data)
super(TreapHashSet, self).__init__(self.keys)
else:
self.keys = set()
def add(self, key):
if key not in self.keys:
self.keys.add(key)
super(TreapHashSet, self).add(key)
def remove(self, key):
self.keys.remove(key)
super(TreapHashSet, self).remove(key)
def discard(self, key):
if key in self.keys:
self.remove(key)
def __contains__(self, key):
return key in self.keys
def __repr__(self):
return "TreapHashSet({})".format(list(self))
class TreapHashMap(TreapMultiSet):
def __init__(self, data=None):
if data:
self.map = dict(data)
super(TreapHashMap, self).__init__(self.map.keys())
else:
self.map = dict()
def __setitem__(self, key, value):
if key not in self.map:
super(TreapHashMap, self).add(key)
self.map[key] = value
def __getitem__(self, key):
return self.map[key]
def add(self, key):
raise TypeError("add on TreapHashMap")
def get(self, key, default=None):
return self.map.get(key, default=default)
def remove(self, key):
self.map.pop(key)
super(TreapHashMap, self).remove(key)
def discard(self, key):
if key in self.map:
self.remove(key)
def __contains__(self, key):
return key in self.map
def __repr__(self):
return "TreapHashMap({})".format(list(self))
left_child = [0]
right_child = [0]
subtree_size = [0]
treap_keys = [0]
treap_prior = [0.0]
def treap_builder(sorted_data):
"""Build a treap in O(n) time using sorted data"""
def build(begin, end):
if begin == end:
return 0
mid = (begin + end) // 2
root = treap_create_node(sorted_data[mid])
left_child[root] = build(begin, mid)
right_child[root] = build(mid + 1, end)
subtree_size[root] = end - begin
# sift down the priorities
ind = root
while True:
lc = left_child[ind]
rc = right_child[ind]
if lc and treap_prior[lc] > treap_prior[ind]:
if rc and treap_prior[rc] > treap_prior[rc]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
treap_prior[ind], treap_prior[lc] = treap_prior[lc], treap_prior[ind]
ind = lc
elif rc and treap_prior[rc] > treap_prior[ind]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
break
return root
return build(0, len(sorted_data))
def treap_create_node(key):
treap_keys.append(key)
treap_prior.append(random.random())
left_child.append(0)
right_child.append(0)
subtree_size.append(1)
return len(treap_keys) - 1
def treap_split(root, key):
left_pos = right_pos = 0
stack = []
while root:
if key < treap_keys[root]:
stack.append(right_pos)
left_child[right_pos] = right_pos = root
root = left_child[root]
else:
stack.append(left_pos)
right_child[left_pos] = left_pos = root
root = right_child[root]
left, right = right_child[0], left_child[0]
stack.append(left_pos)
stack.append(right_pos)
right_child[left_pos] = left_child[right_pos] = right_child[0] = left_child[0] = 0
treap_update_size(stack)
check_size_invariant(left)
check_size_invariant(right)
return left, right
def treap_merge(left, right):
where, pos = left_child, 0
stack = [pos]
while left and right:
if treap_prior[left] > treap_prior[right]:
where[pos] = pos = left
where = right_child
left = right_child[left]
else:
where[pos] = pos = right
where = left_child
right = left_child[right]
stack.append(pos)
where[pos] = left or right
node = left_child[0]
left_child[0] = 0
treap_update_size(stack)
check_size_invariant(node)
return node
def treap_insert(root, key):
if not root:
return treap_create_node(key)
left, right = treap_split(root, key)
return treap_merge(treap_merge(left, treap_create_node(key)), right)
def treap_insert_unique(root, key):
if not root:
return treap_create_node(key), False
left, right = treap_split(root, key)
if left and treap_keys[left] == key:
return treap_merge(left, right), True
return treap_merge(treap_merge(left, treap_create_node(key)), right), False
def treap_erase(root, key):
if not root:
raise KeyError(key)
if treap_keys[root] == key:
return treap_merge(left_child[root], right_child[root])
node = root
stack = [root]
while root and treap_keys[root] != key:
parent = root
root = left_child[root] if key < treap_keys[root] else right_child[root]
stack.append(root)
if not root:
raise KeyError(key)
if root == left_child[parent]:
left_child[parent] = treap_merge(left_child[root], right_child[root])
else:
right_child[parent] = treap_merge(left_child[root], right_child[root])
treap_update_size(stack)
check_size_invariant(node)
return node
def treap_ceiling(root, key):
while root and treap_keys[root] < key:
root = right_child[root]
if not root:
return 0
min_node = root
min_key = treap_keys[root]
while root:
if treap_keys[root] < key:
root = right_child[root]
else:
if treap_keys[root] < min_key:
min_key = treap_keys[root]
min_node = root
root = left_child[root]
return min_node
def treap_higher(root, key):
while root and treap_keys[root] <= key:
root = right_child[root]
if not root:
return 0
min_node = root
min_key = treap_keys[root]
while root:
if treap_keys[root] <= key:
root = right_child[root]
else:
if treap_keys[root] < min_key:
min_key = treap_keys[root]
min_node = root
root = left_child[root]
return min_node
def treap_floor(root, key):
while root and treap_keys[root] > key:
root = left_child[root]
if not root:
return 0
max_node = root
max_key = treap_keys[root]
while root:
if treap_keys[root] > key:
root = left_child[root]
else:
if treap_keys[root] > max_key:
max_key = treap_keys[root]
max_node = root
root = right_child[root]
return max_node
def treap_lower(root, key):
while root and treap_keys[root] >= key:
root = left_child[root]
if not root:
return 0
max_node = root
max_key = treap_keys[root]
while root:
if treap_keys[root] >= key:
root = left_child[root]
else:
if treap_keys[root] > max_key:
max_key = treap_keys[root]
max_node = root
root = right_child[root]
return max_node
def treap_min(root):
if not root:
raise ValueError("min on empty treap")
while left_child[root]:
root = left_child[root]
return root
def treap_max(root):
if not root:
raise ValueError("max on empty treap")
while right_child[root]:
root = right_child[root]
return root
def treap_update_size(path):
for pos in reversed(path):
lc = left_child[pos]
rc = right_child[pos]
left_size = subtree_size[lc] if lc else 0
right_size = subtree_size[rc] if rc else 0
subtree_size[pos] = left_size + 1 + right_size
def check_size_invariant(node):
return
if node == 0:
return 0
lc = left_child[node]
rc = right_child[node]
left_size = subtree_size[lc] if lc else 0
right_size = subtree_size[rc] if rc else 0
assert subtree_size[node] == left_size + 1 + right_size
check_size_invariant(lc)
check_size_invariant(rc)
def treap_find_kth(root, k):
if not root or not (0 <= k < subtree_size[root]):
raise IndexError("treap index out of range")
while True:
lc = left_child[root]
if lc:
if k < subtree_size[lc]:
root = lc
continue
k -= subtree_size[lc]
if k == 0:
return treap_keys[root]
k -= 1
rc = right_child[root]
assert rc and k < subtree_size[rc]
root = rc
def treap_bisect_left(root, key):
index = 0
while root:
if treap_keys[root] < key:
lc = left_child[root]
left_size = subtree_size[lc] if lc else 0
index += left_size + 1
root = right_child[root]
else:
root = left_child[root]
return index
def treap_bisect_right(root, key):
index = 0
while root:
if treap_keys[root] <= key:
lc = left_child[root]
left_size = subtree_size[lc] if lc else 0
index += left_size + 1
root = right_child[root]
else:
root = left_child[root]
return index
# End treap copy and paste
def solve(N, M, messages):
# Initial mn/mx is their initial positions
ans = [[i, i] for i in range(N)]
#friendsList = SortedList()
friendsList = TreapMultiSet()
friendsToTime = {i: i for i in range(N)}
for f, t in friendsToTime.items():
friendsList.add((t, f))
for t, f in enumerate(messages):
index = friendsList.bisect_left((friendsToTime[f], f))
ans[f][1] = max(ans[f][1], index)
friendsList.remove((friendsToTime[f], f))
friendsToTime[f] = -t - 1
friendsList.add((friendsToTime[f], f))
ans[f][0] = min(ans[f][0], 0)
for i, (t, f) in enumerate(friendsList):
ans[f][0] = min(ans[f][0], i)
ans[f][1] = max(ans[f][1], i)
return "\n".join(str(x + 1) + " " + str(y + 1) for x, y in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
messages = [int(x) - 1 for x in input().split()] # 0 indexed
ans = solve(N, M, messages)
print(ans)
```
| 31,875 | [
0.54150390625,
-0.06524658203125,
0.138427734375,
0.5810546875,
-0.24462890625,
-0.9365234375,
-0.421630859375,
0.36962890625,
0.10748291015625,
0.71337890625,
1.1240234375,
-0.177490234375,
0.18505859375,
-0.62939453125,
-0.8720703125,
0.213623046875,
-0.7841796875,
-0.6953125,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.buffer.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = int(1e9)+7
def update(v, w):
while v <= N:
BIT[v] += w
v += (v & (-v))
def getvalue(v):
ANS = 0
while v != 0:
ANS += BIT[v]
v -= (v & (-v))
return ANS
def bisect_on_BIT(x):
if x <= 0:
return 0
ANS = 0
h = 1 << (n - 1)
while h > 0:
if ANS + h <= n and BIT[ANS + h] < x:
x -= BIT[ANS + h]
ANS += h
h //= 2
return ANS + 1
n,m=mdata()
a=mdata()
BIT = [0]*(n+m+1)
N=n+m
pos=[0]*(n+1)
v=[0]*(n+1)
for i in range(1,n+1):
pos[i]=n-i+1
v[i]=i
update(i,1)
for i in range(m):
v[a[i]]=max(v[a[i]],getvalue(n+i)-getvalue(pos[a[i]])+1)
update(pos[a[i]],-1)
pos[a[i]]=n+i+1
update(pos[a[i]],1)
s=set(a)
for i in range(1,n+1):
v[i] = max(v[i], getvalue(n + m) - getvalue(pos[i]) + 1)
if i in s:
print(1,v[i])
else:
print(i,v[i])
```
Yes
| 31,876 | [
0.58544921875,
-0.07672119140625,
0.129150390625,
0.59130859375,
-0.1854248046875,
-0.73779296875,
-0.50244140625,
0.3076171875,
0.1082763671875,
0.68603515625,
1.0537109375,
-0.1964111328125,
0.1534423828125,
-0.63427734375,
-0.8271484375,
0.1942138671875,
-0.74560546875,
-0.68310... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**30, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] > k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n,m=map(int,input().split())
l=list(map(int,input().split()))
se=set(l)
mi=[0]*(n+1)
ma=[0]*(n+1)
pos=[i+m-1 for i in range(n+1)]
for i in range(1,n+1):
if i in se:
mi[i]=1
else:
mi[i]=i
a=[0]*m+[1 for i in range(1,n+1)]+[]
t=m-1
s=SegmentTree(a)
for i in range(m):
w=l[i]
ma[l[i]]=max(ma[l[i]],s.query(0,pos[l[i]]))
last=pos[l[i]]
pos[l[i]]=t
t-=1
s.__setitem__(t+1,1)
s.__setitem__(last,0)
a[t+1]=1
a[last]=0
for i in range(1,n+1):
ma[i]=max(ma[i],s.query(0,pos[i]))
print(mi[i],ma[i])
```
Yes
| 31,877 | [
0.58544921875,
-0.07672119140625,
0.129150390625,
0.59130859375,
-0.1854248046875,
-0.73779296875,
-0.50244140625,
0.3076171875,
0.1082763671875,
0.68603515625,
1.0537109375,
-0.1964111328125,
0.1534423828125,
-0.63427734375,
-0.8271484375,
0.1942138671875,
-0.74560546875,
-0.68310... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
n,m = [int(i) for i in input().split()]
a = [int(i)-1 for i in input().split()]
mini = [i for i in range (1,n+1)]
maxi = [i for i in range (1,n+1)]
for i in a:
mini[i] = 1
s = SortedList()
curr = 100000
for i in range (n):
s.add((curr, i))
prev = [100000] * n
for i in a:
ele = (prev[i], i)
ind = s.bisect_left(ele)
maxi[i] = max(maxi[i], ind+1)
s.remove(ele)
curr-=1
s.add((curr, i))
prev[i] = curr
for i in range (n):
curr = s[i][1]
maxi[curr] = max(maxi[curr], i+1)
maxi[s[-1][1]] = n
for i in range (n):
print(mini[i], maxi[i])
```
Yes
| 31,878 | [
0.58544921875,
-0.07672119140625,
0.129150390625,
0.59130859375,
-0.1854248046875,
-0.73779296875,
-0.50244140625,
0.3076171875,
0.1082763671875,
0.68603515625,
1.0537109375,
-0.1964111328125,
0.1534423828125,
-0.63427734375,
-0.8271484375,
0.1942138671875,
-0.74560546875,
-0.68310... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
# SortedList copied from: https://github.com/grantjenks/python-sortedcontainers/blob/master/sortedcontainers/sortedlist.py
# Minified with pyminifier to fit codeforce char limit
from __future__ import print_function
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
from collections.abc import Sequence, MutableSequence
except ImportError:
from collections import Sequence, MutableSequence
from functools import wraps
from sys import hexversion
if hexversion < 0x03000000:
from itertools import imap as map
from itertools import izip as zip
try:
from thread import get_ident
except ImportError:
from dummy_thread import get_ident
else:
from functools import reduce
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
def recursive_repr(fillvalue="..."):
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
class SortedList(MutableSequence):
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError("inherit SortedKeyList for key argument")
@property
def key(self):
return None
def _reset(self, load):
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(
values[pos : (pos + _load)] for pos in range(0, len(values), _load)
)
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError("{0!r} not in list".format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError("{0!r} not in list".format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError("{0!r} not in list".format(value))
def _delete(self, pos, idx):
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
pos += self._offset
while pos:
if not pos & 1:
total += _index[pos - 1]
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError("list index out of range")
elif idx >= self._len:
raise IndexError("list index out of range")
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = range(start, stop, step)
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
start_list = _lists[start_pos]
stop_idx = start_idx + stop - start
if len(start_list) >= stop_idx:
return start_list[start_idx:stop_idx]
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1) : stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
indices = range(start, stop, step)
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError("list index out of range")
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
message = "use ``del sl[index]`` and ``sl.add(value)`` instead"
raise NotImplementedError(message)
def __iter__(self):
return chain.from_iterable(self._lists)
def __reversed__(self):
return chain.from_iterable(map(reversed, reversed(self._lists)))
def reverse(self):
raise NotImplementedError("use ``reversed(sl)`` instead")
def islice(self, start=None, stop=None, reverse=False):
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(range(min_idx, max_idx))
return map(_lists[min_pos].__getitem__, indices)
indices = range(min_idx, max_idx)
return map(_lists[min_pos].__getitem__, indices)
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
map(_lists[max_pos].__getitem__, max_indices),
)
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, reversed(sublist_indices))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
chain.from_iterable(map(reversed, sublists)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, sublist_indices)
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
chain.from_iterable(sublists),
map(_lists[max_pos].__getitem__, max_indices),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
return self._len
def bisect_left(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
return self.__class__(self)
__copy__ = copy
def append(self, value):
raise NotImplementedError("use ``sl.add(value)`` instead")
def extend(self, values):
raise NotImplementedError("use ``sl.update(values)`` instead")
def insert(self, index, value):
raise NotImplementedError("use ``sl.add(value)`` instead")
def pop(self, index=-1):
if not self._len:
raise IndexError("pop index out of range")
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError("{0!r} is not in list".format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError("{0!r} is not in list".format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError("{0!r} is not in list".format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError("{0!r} is not in list".format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError("{0!r} is not in list".format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
self._update(other)
return self
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
def comparer(self, other):
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = "__{0}__".format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, "==", "equal to")
__ne__ = __make_cmp(ne, "!=", "not equal to")
__lt__ = __make_cmp(lt, "<", "less than")
__gt__ = __make_cmp(gt, ">", "greater than")
__le__ = __make_cmp(le, "<=", "less than or equal to")
__ge__ = __make_cmp(ge, ">=", "greater than or equal to")
__make_cmp = staticmethod(__make_cmp)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values,))
@recursive_repr()
def __repr__(self):
return "{0}({1!r})".format(type(self).__name__, list(self))
def _check(self):
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
print("len", self._len)
print("load", self._load)
print("offset", self._offset)
print("len_index", len(self._index))
print("index", self._index)
print("len_maxes", len(self._maxes))
print("maxes", self._maxes)
print("len_lists", len(self._lists))
print("lists", self._lists)
raise
def identity(value):
return value
class SortedKeyList(SortedList):
def __init__(self, iterable=None, key=identity):
self._key = key
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._keys = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=identity):
return object.__new__(cls)
@property
def key(self):
return self._key
def clear(self):
self._len = 0
del self._lists[:]
del self._keys[:]
del self._maxes[:]
del self._index[:]
_clear = clear
def add(self, value):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
key = self._key(value)
if _maxes:
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_keys[pos].append(key)
_maxes[pos] = key
else:
idx = bisect_right(_keys[pos], key)
_lists[pos].insert(idx, value)
_keys[pos].insert(idx, key)
self._expand(pos)
else:
_lists.append([value])
_keys.append([key])
_maxes.append(key)
self._len += 1
def _expand(self, pos):
_lists = self._lists
_keys = self._keys
_index = self._index
if len(_keys[pos]) > (self._load << 1):
_maxes = self._maxes
_load = self._load
_lists_pos = _lists[pos]
_keys_pos = _keys[pos]
half = _lists_pos[_load:]
half_keys = _keys_pos[_load:]
del _lists_pos[_load:]
del _keys_pos[_load:]
_maxes[pos] = _keys_pos[-1]
_lists.insert(pos + 1, half)
_keys.insert(pos + 1, half_keys)
_maxes.insert(pos + 1, half_keys[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort(key=self._key)
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(
values[pos : (pos + _load)] for pos in range(0, len(values), _load)
)
_keys.extend(list(map(self._key, _list)) for _list in _lists)
_maxes.extend(sublist[-1] for sublist in _keys)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
_maxes = self._maxes
if not _maxes:
return False
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return False
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return False
if _lists[pos][idx] == value:
return True
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return False
len_sublist = len(_keys[pos])
idx = 0
def discard(self, value):
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
def remove(self, value):
_maxes = self._maxes
if not _maxes:
raise ValueError("{0!r} not in list".format(value))
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError("{0!r} not in list".format(value))
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError("{0!r} not in list".format(value))
if _lists[pos][idx] == value:
self._delete(pos, idx)
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError("{0!r} not in list".format(value))
len_sublist = len(_keys[pos])
idx = 0
def _delete(self, pos, idx):
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
_index = self._index
keys_pos = _keys[pos]
lists_pos = _lists[pos]
del keys_pos[idx]
del lists_pos[idx]
self._len -= 1
len_keys_pos = len(keys_pos)
if len_keys_pos > (self._load >> 1):
_maxes[pos] = keys_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_keys) > 1:
if not pos:
pos += 1
prev = pos - 1
_keys[prev].extend(_keys[pos])
_lists[prev].extend(_lists[pos])
_maxes[prev] = _keys[prev][-1]
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_keys_pos:
_maxes[pos] = keys_pos[-1]
else:
del _lists[pos]
del _keys[pos]
del _maxes[pos]
del _index[:]
def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
min_key = self._key(minimum) if minimum is not None else None
max_key = self._key(maximum) if maximum is not None else None
return self._irange_key(
min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse,
)
def irange_key(
self, min_key=None, max_key=None, inclusive=(True, True), reverse=False
):
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
_irange_key = irange_key
def bisect_left(self, value):
return self._bisect_key_left(self._key(value))
def bisect_right(self, value):
return self._bisect_key_right(self._key(value))
bisect = bisect_right
def bisect_key_left(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._keys[pos], key)
return self._loc(pos, idx)
_bisect_key_left = bisect_key_left
def bisect_key_right(self, key):
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, key)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._keys[pos], key)
return self._loc(pos, idx)
bisect_key = bisect_key_right
_bisect_key_right = bisect_key_right
def count(self, value):
_maxes = self._maxes
if not _maxes:
return 0
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
return 0
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
total = 0
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return total
if _lists[pos][idx] == value:
total += 1
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return total
len_sublist = len(_keys[pos])
idx = 0
def copy(self):
return self.__class__(self, key=self._key)
__copy__ = copy
def index(self, value, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError("{0!r} is not in list".format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError("{0!r} is not in list".format(value))
_maxes = self._maxes
key = self._key(value)
pos = bisect_left(_maxes, key)
if pos == len(_maxes):
raise ValueError("{0!r} is not in list".format(value))
stop -= 1
_lists = self._lists
_keys = self._keys
idx = bisect_left(_keys[pos], key)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
raise ValueError("{0!r} is not in list".format(value))
if _lists[pos][idx] == value:
loc = self._loc(pos, idx)
if start <= loc <= stop:
return loc
elif loc > stop:
break
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
raise ValueError("{0!r} is not in list".format(value))
len_sublist = len(_keys[pos])
idx = 0
raise ValueError("{0!r} is not in list".format(value))
def __add__(self, other):
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values, key=self._key)
__radd__ = __add__
def __mul__(self, num):
values = reduce(iadd, self._lists, []) * num
return self.__class__(values, key=self._key)
def __reduce__(self):
values = reduce(iadd, self._lists, [])
return (type(self), (values, self.key))
@recursive_repr()
def __repr__(self):
type_name = type(self).__name__
return "{0}({1!r}, key={2!r})".format(type_name, list(self), self._key)
def _check(self):
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists) == len(self._keys)
assert self._len == sum(len(sublist) for sublist in self._lists)
for sublist in self._keys:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
for pos in range(1, len(self._keys)):
assert self._keys[pos - 1][-1] <= self._keys[pos][0]
for val_sublist, key_sublist in zip(self._lists, self._keys):
assert len(val_sublist) == len(key_sublist)
for val, key in zip(val_sublist, key_sublist):
assert self._key(val) == key
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._keys[pos][-1]
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
traceback.print_exc(file=sys.stdout)
print("len", self._len)
print("load", self._load)
print("offset", self._offset)
print("len_index", len(self._index))
print("index", self._index)
print("len_maxes", len(self._maxes))
print("maxes", self._maxes)
print("len_keys", len(self._keys))
print("keys", self._keys)
print("len_lists", len(self._lists))
print("lists", self._lists)
raise
SortedListWithKey = SortedKeyList
# Created by pyminifier (https://github.com/liftoff/pyminifier)
################################ End copy and paste
import io
import os
from collections import Counter, defaultdict, deque
# from sortedcontainers import SortedList
def solve(N, M, messages):
# Initial mn/mx is their initial positions
ans = [[i, i] for i in range(N)]
friendsList = SortedList()
friendsToTime = {i: i for i in range(N)}
for f, t in friendsToTime.items():
friendsList.add((t, f))
for t, f in enumerate(messages):
index = friendsList.bisect_left((friendsToTime[f], f))
ans[f][1] = max(ans[f][1], index)
friendsList.remove((friendsToTime[f], f))
friendsToTime[f] = -t - 1
friendsList.add((friendsToTime[f], f))
ans[f][0] = min(ans[f][0], 0)
for i, (t, f) in enumerate(friendsList):
ans[f][0] = min(ans[f][0], i)
ans[f][1] = max(ans[f][1], i)
return "\n".join(str(x + 1) + " " + str(y + 1) for x, y in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
messages = [int(x) - 1 for x in input().split()] # 0 indexed
ans = solve(N, M, messages)
print(ans)
```
Yes
| 31,879 | [
0.58544921875,
-0.07672119140625,
0.129150390625,
0.59130859375,
-0.1854248046875,
-0.73779296875,
-0.50244140625,
0.3076171875,
0.1082763671875,
0.68603515625,
1.0537109375,
-0.1964111328125,
0.1534423828125,
-0.63427734375,
-0.8271484375,
0.1942138671875,
-0.74560546875,
-0.68310... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
nm = list(map(int ,input().split()))
n = nm[0]
m = nm[1]
messages = list(map(int, input().split()))
min_pos = []
max_pos = []
config = []
for item1 in range(n):
min_pos.append(0)
max_pos.append(0)
for item2 in range(n):
config.append(item2 + 1)
for num1 in range(n):
if num1+1 in messages:
min_pos[num1] = 1
else:
min_pos[num1] = config.index(num1+1) + 1
max_pos[num1] = config.index(num1+1) + 1
for num2 in messages:
if num2 == config[0]:
continue
else:
temp = []
temp.append(num2)
config.remove(num2)
config = temp + config
for item in config:
if min_pos[item-1] > config.index(item) + 1:
min_pos[item-1] = config.index(item) + 1
if max_pos[item-1] < config.index(item) + 1:
max_pos[item-1] = config.index(item) + 1
for item in zip(min_pos,max_pos):
print(item)
```
No
| 31,880 | [
0.58544921875,
-0.07672119140625,
0.129150390625,
0.59130859375,
-0.1854248046875,
-0.73779296875,
-0.50244140625,
0.3076171875,
0.1082763671875,
0.68603515625,
1.0537109375,
-0.1964111328125,
0.1534423828125,
-0.63427734375,
-0.8271484375,
0.1942138671875,
-0.74560546875,
-0.68310... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import defaultdict
class Bit:
def __init__(self,n):
self.size = n
self.tree = [0]*(n+1)
def sum(self,i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self,i,x):
while i <= self.size:
self.tree[i] += x
i += i & -i
n,m = map(int,input().split())
a = list(map(int,input().split()))
ls = []
if a[0] != 1:
ls.append(a[0])
for i in range(1,m):
if a[i-1] != a[i]:
ls.append(a[i])
m = len(ls)
dc = defaultdict(int)
bit = Bit(n+1)
ansls = [[i,i] for i in range(n+1)]
if m == 0:
for i in range(1,n+1):
print(*ansls[i])
exit()
for i in range(m):
x = ls[i]
if dc[x] == 0:
dc[x] = i+1
ansls[x] = [1,x+bit.sum(n)-bit.sum(x)]
bit.add(x,1)
else:
ansls[x][1] = min(n,max(ansls[x][1],i+1-dc[x]))
dc[x] = i+1
for i in range(1,n+1):
if dc[i] == 0:
ansls[i][1] = min(n,i+bit.sum(n)-bit.sum(i))
else:
ansls[i][1] = min(n,max(ansls[i][1],m+1-dc[i]))
for i in range(1,n+1):
print(*ansls[i])
```
No
| 31,881 | [
0.58544921875,
-0.07672119140625,
0.129150390625,
0.59130859375,
-0.1854248046875,
-0.73779296875,
-0.50244140625,
0.3076171875,
0.1082763671875,
0.68603515625,
1.0537109375,
-0.1964111328125,
0.1534423828125,
-0.63427734375,
-0.8271484375,
0.1942138671875,
-0.74560546875,
-0.68310... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
n,m=map(int,input().split())
friends=[[i,i] for i in range(n)]
p=[i for i in range(n)]
s=list(map(int,input().split()))
for i in range(m):
j=s[i]
p.remove(j-1)
p=[j-1]+p
friends[j-1][0]=0
for sb in range(1,j):
if friends[sb][1]<p.index(sb):
friends[sb][1]=p.index(sb)
for i in friends:
print(i[0]+1,i[1]+1)
```
No
| 31,882 | [
0.58544921875,
-0.07672119140625,
0.129150390625,
0.59130859375,
-0.1854248046875,
-0.73779296875,
-0.50244140625,
0.3076171875,
0.1082763671875,
0.68603515625,
1.0537109375,
-0.1964111328125,
0.1534423828125,
-0.63427734375,
-0.8271484375,
0.1942138671875,
-0.74560546875,
-0.68310... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has n friends, numbered from 1 to n.
Recall that a permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array.
So his recent chat list can be represented with a permutation p of size n. p_1 is the most recent friend Polycarp talked to, p_2 is the second most recent and so on.
Initially, Polycarp's recent chat list p looks like 1, 2, ..., n (in other words, it is an identity permutation).
After that he receives m messages, the j-th message comes from the friend a_j. And that causes friend a_j to move to the first position in a permutation, shifting everyone between the first position and the current position of a_j by 1. Note that if the friend a_j is in the first position already then nothing happens.
For example, let the recent chat list be p = [4, 1, 5, 3, 2]:
* if he gets messaged by friend 3, then p becomes [3, 4, 1, 5, 2];
* if he gets messaged by friend 4, then p doesn't change [4, 1, 5, 3, 2];
* if he gets messaged by friend 2, then p becomes [2, 4, 1, 5, 3].
For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 3 ⋅ 10^5) — the number of Polycarp's friends and the number of received messages, respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n) — the descriptions of the received messages.
Output
Print n pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.
Examples
Input
5 4
3 5 1 4
Output
1 3
2 5
1 4
1 5
1 5
Input
4 3
1 2 4
Output
1 3
1 2
3 4
1 4
Note
In the first example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4, 5]
* [3, 1, 2, 4, 5]
* [5, 3, 1, 2, 4]
* [1, 5, 3, 2, 4]
* [4, 1, 5, 3, 2]
So, for example, the positions of the friend 2 are 2, 3, 4, 4, 5, respectively. Out of these 2 is the minimum one and 5 is the maximum one. Thus, the answer for the friend 2 is a pair (2, 5).
In the second example, Polycarp's recent chat list looks like this:
* [1, 2, 3, 4]
* [1, 2, 3, 4]
* [2, 1, 3, 4]
* [4, 2, 1, 3]
Submitted Solution:
```
from collections import deque
from bisect import bisect_left
n,m = map(int, input().split())
alist = list(map(int, input().split()))
posmax = {}
moved = []
pos = {}
c = 0
for idx,a in enumerate(alist):
i = bisect_left(moved, a)
if i == c or moved[i] != a:
posmax[a] = a+c-i
moved.insert(i,a)
c+=1
else:
posmax[a] = max(posmax[a], idx-pos[a])
pos[a] = idx
lines = deque()
d = 0
for i in range(n,0,-1):
a,b = i,i
if i in pos:
a,b = 1,max(posmax[i],c-pos[i])
d+=1
else:
b+=d
lines.appendleft("{} {}".format(a,b))
print('\n'.join(lines))
```
No
| 31,883 | [
0.58544921875,
-0.07672119140625,
0.129150390625,
0.59130859375,
-0.1854248046875,
-0.73779296875,
-0.50244140625,
0.3076171875,
0.1082763671875,
0.68603515625,
1.0537109375,
-0.1964111328125,
0.1534423828125,
-0.63427734375,
-0.8271484375,
0.1942138671875,
-0.74560546875,
-0.68310... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Tags: implementation, two pointers
Correct Solution:
```
for _ in range (int(input())):
n=int(input())
arr=list(map(int,input().split()[:n]))
arr1=[0]*n
i=0
if n%2!=0:
for j in range (0,n,2):
arr1[j]=arr[i]
i+=1
for k in range (n-2,0,-2):
arr1[k]=arr[i]
i+=1
else:
for j in range (0,n,2):
arr1[j]=arr[i]
i+=1
for k in range (n-1,0,-2):
arr1[k]=arr[i]
i+=1
print(*arr1)
```
| 31,952 | [
0.298095703125,
-0.05047607421875,
0.29296875,
0.31591796875,
-0.451171875,
-0.40478515625,
-0.2274169921875,
0.11004638671875,
0.1163330078125,
0.81787109375,
0.7265625,
0.0182342529296875,
0.08984375,
-0.86865234375,
-0.63525390625,
-0.353515625,
-0.54443359375,
-0.5595703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Tags: implementation, two pointers
Correct Solution:
```
test_cases = int(input())
for i in range(test_cases):
size = int(input())
arr = list(map(int, input().split()))
ans = []
for i in range(size // 2):
ans.append(str(arr[i]))
ans.append(str(arr[size-i-1]))
if size % 2 != 0:
ans = ans + [str(arr[size // 2])]
print(' '.join(ans))
```
| 31,953 | [
0.298095703125,
-0.05047607421875,
0.29296875,
0.31591796875,
-0.451171875,
-0.40478515625,
-0.2274169921875,
0.11004638671875,
0.1163330078125,
0.81787109375,
0.7265625,
0.0182342529296875,
0.08984375,
-0.86865234375,
-0.63525390625,
-0.353515625,
-0.54443359375,
-0.5595703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Tags: implementation, two pointers
Correct Solution:
```
t = int(input())
ans = []
for i in range(t):
n = int(input())
b = input().split()
i = 0
j = len(b) - 1
res = []
while i < j:
res.append(b[i])
res.append(b[j])
i += 1
j -= 1
if i == j:
res.append(b[i])
ans.append(res)
for a in ans:
print(" ".join(a))
```
| 31,954 | [
0.298095703125,
-0.05047607421875,
0.29296875,
0.31591796875,
-0.451171875,
-0.40478515625,
-0.2274169921875,
0.11004638671875,
0.1163330078125,
0.81787109375,
0.7265625,
0.0182342529296875,
0.08984375,
-0.86865234375,
-0.63525390625,
-0.353515625,
-0.54443359375,
-0.5595703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Tags: implementation, two pointers
Correct Solution:
```
from collections import deque
def solution(n, blist):
deq = deque(blist)
ans = []
for i in range(len(blist)):
if i % 2 == 0:
ans.append(deq.popleft())
else:
ans.append(deq.pop())
return ans
t = int(input())
for tt in range(t):
n = int(input())
blist = list(map(int, input().split()))
for num in solution(n, blist):
print(num, end=' ')
print()
```
| 31,955 | [
0.298095703125,
-0.05047607421875,
0.29296875,
0.31591796875,
-0.451171875,
-0.40478515625,
-0.2274169921875,
0.11004638671875,
0.1163330078125,
0.81787109375,
0.7265625,
0.0182342529296875,
0.08984375,
-0.86865234375,
-0.63525390625,
-0.353515625,
-0.54443359375,
-0.5595703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Tags: implementation, two pointers
Correct Solution:
```
t=int(input())
while(t>0):
n=int(input())
arr=list(map(int,input().strip().split()))
l=len(arr)
l1=[]
l2=[]
flag=0
if(l%2!=0):
x=arr[l//2]
flag=1
l1=arr[:l//2]
l2=arr[(l//2)+1:]
else:
l1=arr[:l//2]
l2=arr[l//2:]
l2.reverse()
num=n
j=0
i=0
ans=[0]*n
p=len(l1)
while(p>0):
ans[j]=l1[i]
j+=1
ans[j]=l2[i]
j+=1
i+=1
p-=1
if(flag==1):
ans[j]=x
print(*ans)
t-=1
```
| 31,956 | [
0.298095703125,
-0.05047607421875,
0.29296875,
0.31591796875,
-0.451171875,
-0.40478515625,
-0.2274169921875,
0.11004638671875,
0.1163330078125,
0.81787109375,
0.7265625,
0.0182342529296875,
0.08984375,
-0.86865234375,
-0.63525390625,
-0.353515625,
-0.54443359375,
-0.5595703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Tags: implementation, two pointers
Correct Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
l1=l[::-1]
k=[]
o=0
j=0
for i in range(n):
if(i%2==0):
k.append(l[o])
o+=1
else:
k.append(l1[j])
j+=1
for i in k:
print(i,end=" ")
print()
```
| 31,957 | [
0.298095703125,
-0.05047607421875,
0.29296875,
0.31591796875,
-0.451171875,
-0.40478515625,
-0.2274169921875,
0.11004638671875,
0.1163330078125,
0.81787109375,
0.7265625,
0.0182342529296875,
0.08984375,
-0.86865234375,
-0.63525390625,
-0.353515625,
-0.54443359375,
-0.5595703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Tags: implementation, two pointers
Correct Solution:
```
import math ;
t = int(input());
while(t > 0 ):
t-=1 ;
n = int(input());
a = list(map(int , input().split(' ')))
ans = []
for i in range(int(n/2)):
ans.append(a[i]);
ans.append(a[n-1-i]);
if(n%2 > 0 ):
ans.append(a[math.floor(n/2)])
print((*ans))
```
| 31,958 | [
0.298095703125,
-0.05047607421875,
0.29296875,
0.31591796875,
-0.451171875,
-0.40478515625,
-0.2274169921875,
0.11004638671875,
0.1163330078125,
0.81787109375,
0.7265625,
0.0182342529296875,
0.08984375,
-0.86865234375,
-0.63525390625,
-0.353515625,
-0.54443359375,
-0.5595703125,
... | 24 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Tags: implementation, two pointers
Correct Solution:
```
n = int(input())
for i in range(n):
t = int(input())
s = input().split()
q = 0
w = t-1
if abs(q-w) == 1:
print(s[q], s[w])
elif len(s) == 1:
print(*s)
else:
while q != w:
print(s[q],s[w],end = ' ')
q+=1
w-=1
if q == w:
print(s[q])
break
elif abs(q-w) == 1:
print(s[q], s[w])
break
```
| 31,959 | [
0.298095703125,
-0.05047607421875,
0.29296875,
0.31591796875,
-0.451171875,
-0.40478515625,
-0.2274169921875,
0.11004638671875,
0.1163330078125,
0.81787109375,
0.7265625,
0.0182342529296875,
0.08984375,
-0.86865234375,
-0.63525390625,
-0.353515625,
-0.54443359375,
-0.5595703125,
... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Submitted Solution:
```
#import numpy as np
#import collections
#import sys
# =============================================================================
def get_primeFactor(n):
res=[1]
x=2
while x*x<=n:
while n%x==0:
res.append(x)
n//=x
x+=1
if n>1:res.append(n)
return res
def getFactor(n):
res={1,n}
x=2
while x*x<=n:
if n%x==0:
res.add(x)
res.add(n//x)
x+=1
return res
def solve():
n=int(input())
arr=list(map(int,input().split()))
if len(arr)<=2:return ' '.join(str(i) for i in arr)
res=''
for i in range((n//2)):
res+='{} '.format(arr[i])
res+='{} '.format(arr[n-i-1])
if n%2==0:return res
else :return res+str(arr[n//2])
for _ in range(int(input())):
print(solve())
```
Yes
| 31,960 | [
0.39892578125,
0.056121826171875,
0.231201171875,
0.210693359375,
-0.5224609375,
-0.295654296875,
-0.351318359375,
0.1614990234375,
0.09375,
0.8212890625,
0.56787109375,
0.0643310546875,
0.06475830078125,
-0.82958984375,
-0.5927734375,
-0.419921875,
-0.546875,
-0.513671875,
-0.77... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Submitted Solution:
```
t = int(input())
list = []
for i in range(t):
n = int(input())
s = input()
s = s.split(' ')
i = 0
j = -1
n_s = ""
if n % 2 == 0:
while(i+1 <= n//2):
n_s = n_s + s[i] + ' ' + s[j] + ' '
i = i + 1
j = j - 1
n_s = n_s[0:-1]
else:
while(i+1 <= n//2):
n_s = n_s + s[i] + ' ' + s[j] + ' '
i = i + 1
j = j - 1
n_s = n_s + s[i]
list.append(n_s)
for item in list:
print(item)
```
Yes
| 31,961 | [
0.39892578125,
0.056121826171875,
0.231201171875,
0.210693359375,
-0.5224609375,
-0.295654296875,
-0.351318359375,
0.1614990234375,
0.09375,
0.8212890625,
0.56787109375,
0.0643310546875,
0.06475830078125,
-0.82958984375,
-0.5927734375,
-0.419921875,
-0.546875,
-0.513671875,
-0.77... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Submitted Solution:
```
import math
n=int(input())
for i in range(2*n):
m=input()
p=[]
if i%2==1:
a=m.split()
q=math.ceil(len(a)/2)
x=a[:q]
y=list(a[len(a):q-1:-1])
for j in range(len(a)):
if j%2==0:
p.append(x.pop(0))
elif j%2==1:
p.append(y.pop(0))
print(' '.join(p))
```
Yes
| 31,962 | [
0.39892578125,
0.056121826171875,
0.231201171875,
0.210693359375,
-0.5224609375,
-0.295654296875,
-0.351318359375,
0.1614990234375,
0.09375,
0.8212890625,
0.56787109375,
0.0643310546875,
0.06475830078125,
-0.82958984375,
-0.5927734375,
-0.419921875,
-0.546875,
-0.513671875,
-0.77... | 24 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has a favorite sequence a[1 ... n] consisting of n integers. He wrote it out on the whiteboard as follows:
* he wrote the number a_1 to the left side (at the beginning of the whiteboard);
* he wrote the number a_2 to the right side (at the end of the whiteboard);
* then as far to the left as possible (but to the right from a_1), he wrote the number a_3;
* then as far to the right as possible (but to the left from a_2), he wrote the number a_4;
* Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.
<image> The beginning of the result looks like this (of course, if n ≥ 4).
For example, if n=7 and a=[3, 1, 4, 1, 5, 9, 2], then Polycarp will write a sequence on the whiteboard [3, 4, 5, 2, 9, 1, 1].
You saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.
Input
The first line contains a single positive integer t (1 ≤ t ≤ 300) — the number of test cases in the test. Then t test cases follow.
The first line of each test case contains an integer n (1 ≤ n ≤ 300) — the length of the sequence written on the whiteboard.
The next line contains n integers b_1, b_2,…, b_n (1 ≤ b_i ≤ 10^9) — the sequence written on the whiteboard.
Output
Output t answers to the test cases. Each answer — is a sequence a that Polycarp wrote out on the whiteboard.
Example
Input
6
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
Output
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
Note
In the first test case, the sequence a matches the sequence from the statement. The whiteboard states after each step look like this:
[3] ⇒ [3, 1] ⇒ [3, 4, 1] ⇒ [3, 4, 1, 1] ⇒ [3, 4, 5, 1, 1] ⇒ [3, 4, 5, 9, 1, 1] ⇒ [3, 4, 5, 2, 9, 1, 1].
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
seq=list(map(int, input().split()))
while seq:
print(seq.pop(0), end=' ')
if seq:
print(seq.pop(len(seq)-1), end=' ')
print()
```
Yes
| 31,963 | [
0.39892578125,
0.056121826171875,
0.231201171875,
0.210693359375,
-0.5224609375,
-0.295654296875,
-0.351318359375,
0.1614990234375,
0.09375,
0.8212890625,
0.56787109375,
0.0643310546875,
0.06475830078125,
-0.82958984375,
-0.5927734375,
-0.419921875,
-0.546875,
-0.513671875,
-0.77... | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.