message stringlengths 2 43.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 853 107k | cluster float64 24 24 | __index_level_0__ int64 1.71k 214k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given). | instruction | 0 | 56,460 | 24 | 112,920 |
Tags: bitmasks, combinatorics, dp
Correct Solution:
```
from itertools import combinations
def out1(a,b,c):
if a<0 or b<0 or c<0:
return 0
if a==1 and b==0 and c==0:
return 1
return a*(out2(a-1,b,c)+out3(a-1,b,c))
def out2(a,b,c):
if a<0 or b<0 or c<0:
return 0
if a==0 and b==1 and c==0:
return 1
return b*(out1(a,b-1,c)+out3(a,b-1,c))
def out3(a,b,c):
if a<0 or b<0 or c<0:
return 0
if a==0 and b==0 and c==1:
return 1
return c*(out2(a,b,c-1)+out1(a,b,c-1))
def column(matrix, i):
return [row[i] for row in matrix]
N, T = [int(x) for x in input().split()]
A = []
s = 0
for i in range(N):
A.append([int(x) for x in input().split()])
for i in range(1,N+1):
comb = list(combinations(A, i))
for x in comb:
if sum(column(x,0))==T:
a = column(x,1).count(1)
b = column(x,1).count(2)
c = column(x,1).count(3)
s+=(out1(a,b,c)+out2(a,b,c)+out3(a,b,c))
print(s%1000000007)
``` | output | 1 | 56,460 | 24 | 112,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given). | instruction | 0 | 56,461 | 24 | 112,922 |
Tags: bitmasks, combinatorics, dp
Correct Solution:
```
def popcount(i):
assert 0 <= i < 0x100000000
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
N, T = map(int, input().split())
TG = [list(map(int, input().split())) for _ in range(N)]
mod = 10**9+7
dp = [[0]*(2**N) for _ in range(4)]
for i in range(1, 4):
dp[i][0] = 1
for S in range(2**N):
if popcount(S) == 1:
dp[TG[(S&(-S)).bit_length() - 1][1]][S] = 1
for i in range(1, 4):
for j in range(N):
if S & (2**j) or i == TG[j][1]:
continue
dp[TG[j][1]][S|(2**j)] = (dp[TG[j][1]][S|(2**j)] + dp[i][S]) % mod
table = [0]*(2**N)
for S in range(2**N):
table[S] = sum(TG[j][0] for j in range(N) if 2**j & S)
ans = 0
for S in range(2**N):
if table[S] == T:
for i in range(1, 4):
ans = (ans + dp[i][S]) % mod
print(ans)
``` | output | 1 | 56,461 | 24 | 112,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given). | instruction | 0 | 56,462 | 24 | 112,924 |
Tags: bitmasks, combinatorics, dp
Correct Solution:
```
from itertools import combinations
def findsum(comb):
sum = 0
for song in comb:
sum += song[0]
return sum
def finda(a,b,c):
if a == 0:
return 0
if a == 1 and b == 0 and c == 0:
return 1
else:
return (a * findb(a-1,b,c)+ a*findc(a-1,b,c))
def findb(a,b,c):
if b == 0:
return 0
if b == 1 and a == 0 and c == 0:
return 1
else:
return (b * finda(a,b-1,c)+ b*findc(a,b-1,c))
def findc(a,b,c):
if c == 0:
return 0
if c == 1 and a == 0 and b == 0:
return 1
else:
return (c * finda(a,b,c-1)+ c*findb(a,b,c-1))
n, T = map(int,input().split())
songs = []
total_combinations = 0
for i in range(n):
t, g = map(int,input().split())
songs.append([t,g])
for i in range(1, n+1):
allcomb = list(combinations(songs,i))
for comb in allcomb:
sum = findsum(comb)
if sum == T:
a = 0
b = 0
c = 0
for song in comb:
if song[1] == 1:
a += 1
elif song[1] == 2:
b += 1
else:
c += 1
total_combinations += finda(a,b,c)+findb(a,b,c)+findc(a,b,c)
total_combinations = total_combinations%1000000007
print(total_combinations)
``` | output | 1 | 56,462 | 24 | 112,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given). | instruction | 0 | 56,463 | 24 | 112,926 |
Tags: bitmasks, combinatorics, dp
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def main():
mod = 10**9+7
n,T = map(int,input().split())
y = 1<<n
dp = [[0]*3 for _ in range(y)]
# already taken ; genre
peo = [list(map(int,input().split())) for _ in range(n)]
# duration ; genre
for ind,i in enumerate(peo):
peo[ind][1] -= 1
dp[1<<ind][i[1]] = 1
for i in range(y):
for j in range(3):
if not dp[i][j]:
continue
mask = 1
for k in range(n):
if i&mask or peo[k][1] == j:
mask <<= 1
continue
dp[i|mask][peo[k][1]] = (dp[i|mask][peo[k][1]]+dp[i][j])%mod
mask <<= 1
ans = 0
for i in range(y):
ans1,mask = 0,1
for j in range(n):
if i&mask:
ans1 += peo[j][0]
mask <<= 1
if ans1 == T:
ans = (ans+sum(dp[i]))%mod
print(ans)
#Fast IO Region
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")
if __name__ == '__main__':
main()
``` | output | 1 | 56,463 | 24 | 112,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given). | instruction | 0 | 56,464 | 24 | 112,928 |
Tags: bitmasks, combinatorics, dp
Correct Solution:
```
from math import factorial
def lol(n):
if n == 1:
yield [0]
yield [1]
else:
for p in lol(n - 1):
p.append(0)
yield p
p[-1] = 1
yield p
p.pop()
def sp(g1, g2, g3, f):
if g1 == 0:
if g2 == g3:
return 2
elif abs(g2 - g3) == 1:
return 1
else:
return 0
elif g2 == 0:
if g1 == g3:
return 2
elif abs(g1 - g3) == 1:
return 1
else:
return 0
elif g3 == 0:
if g2 == g1:
return 2
elif abs(g2 - g1) == 1:
return 1
else:
return 0
else:
if f == 1:
b = sp(g1, g2 - 1, g3, 2)
c = sp(g1, g2, g3 - 1, 3)
return b + c
elif f == 2:
a = sp(g1 - 1, g2, g3, 1)
c = sp(g1, g2, g3 - 1, 3)
return a + c
elif f == 3:
a = sp(g1 - 1, g2, g3, 1)
b = sp(g1, g2 - 1, g3, 2)
return a + b
else:
a = sp(g1 - 1, g2, g3, 1)
b = sp(g1, g2 - 1, g3, 2)
c = sp(g1, g2, g3 - 1, 3)
return a + b + c
n, T = map(int, input().split())
S = []
cnt = 0
M = 10 ** 9 + 7
for i in range(n):
S.append(list(map(int, input().split())))
for p in lol(n):
d = 0
g1, g2, g3 = 0, 0, 0
for i in range(n):
if p[i]:
d += S[i][0]
if S[i][1] == 1:
g1 += 1
elif S[i][1] == 2:
g2 += 1
elif S[i][1] == 3:
g3 += 1
if d == T:
cnt += factorial(g1) * factorial(g2) * factorial(g3) * sp(g1, g2, g3, 0)
cnt %= M
print(cnt)
``` | output | 1 | 56,464 | 24 | 112,929 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given). | instruction | 0 | 56,465 | 24 | 112,930 |
Tags: bitmasks, combinatorics, dp
Correct Solution:
```
n,tnow=map(int,input().split())
left=int("".join(["1" for i in range(n)]),2)
arr=[]
dp={}
for i in range(n):
a,b=map(int,input().split())
arr.append([a,b])
def recur(tnow,prevgenre,left):
key=str(left)+"_"+str(prevgenre)
if tnow==0:
return 1
elif key in dp:
return dp[key]
else:
ans=0
for i in range(n):
if (left&(1<<i))!=0:
if arr[i][0]<=tnow and arr[i][1]!=prevgenre:
left=left&(~(1<<i))
ans+=recur(tnow-arr[i][0],arr[i][1],left)
left=left|(1<<i)
dp[key]= ans
return ans
print(recur(tnow,4,left)%(10**9+7))
``` | output | 1 | 56,465 | 24 | 112,931 |
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.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given).
Submitted Solution:
```
from functools import lru_cache
P = 10**9+7
N, T = map(int, input().split())
A = [[], [], []]
X = []
for _ in range(N):
t, g = map(int, input().split())
X.append((t, g))
@lru_cache(maxsize=None)
def calc(x, pr, t):
if t < 0:
return 0
if t == 0:
return 1
if x == 0:
return 0
ans = 0
for i in range(15):
if x & (1<<i):
if X[i][1] != pr:
y = x ^ (1<<i)
ans = (ans + calc(y, X[i][1], t-X[i][0])) % P
return ans
print(calc(2**N-1, -1, T))
``` | instruction | 0 | 56,466 | 24 | 112,932 |
Yes | output | 1 | 56,466 | 24 | 112,933 |
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.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given).
Submitted Solution:
```
print(1)
A = [i for i in range(1, 2 * 10 ** 5 + 1)]
print(200000)
print(*A)
``` | instruction | 0 | 56,467 | 24 | 112,934 |
No | output | 1 | 56,467 | 24 | 112,935 |
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.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given).
Submitted Solution:
```
from itertools import combinations
def findsum(comb):
sum = 0
for song in comb:
sum += song[0]
return sum
def finda(a,b,c):
if a == 0:
return 0
if a == 1 and b == 0 and c == 0:
return 1
else:
return (a * findb(a-1,b,c)+ a*findc(a-1,b,c))
def findb(a,b,c):
if b == 0:
return 0
if b == 1 and a == 0 and c == 0:
return 1
else:
return (b * finda(a,b-1,c)+ b*findc(a,b-1,c))
def findc(a,b,c):
if c == 0:
return 0
if c == 1 and a == 0 and b == 0:
return 1
else:
return (c * finda(a,b,c-1)+ c*findb(a,b,c-1))
n, T = map(int,input().split())
songs = []
total_combinations = 0
for i in range(n):
t, g = map(int,input().split())
songs.append([t,g])
for i in range(1, n+1):
allcomb = list(combinations(songs,i))
for comb in allcomb:
sum = findsum(comb)
if sum == T:
a = 0
b = 0
c = 0
for song in comb:
if song[1] == 1:
a += 1
elif song[1] == 2:
b += 1
else:
c += 1
total_combinations += finda(a,b,c)+findb(a,b,c)+findc(a,b,c)
print(total_combinations)
``` | instruction | 0 | 56,468 | 24 | 112,936 |
No | output | 1 | 56,468 | 24 | 112,937 |
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.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given).
Submitted Solution:
```
print ("Down Journey :)\n" * 1)
``` | instruction | 0 | 56,469 | 24 | 112,938 |
No | output | 1 | 56,469 | 24 | 112,939 |
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.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 β€ t_i β€ 15), g_i is its genre (1 β€ g_i β€ 3).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
Input
The first line of the input contains two integers n and T (1 β€ n β€ 15, 1 β€ T β€ 225) β the number of songs in the player and the required total duration, respectively.
Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 β€ t_i β€ 15, 1 β€ g_i β€ 3) β the duration of the i-th song and its genre, respectively.
Output
Output one integer β the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).
Examples
Input
3 3
1 1
1 2
1 3
Output
6
Input
3 3
1 1
1 1
1 3
Output
2
Input
4 10
5 3
2 1
3 2
5 1
Output
10
Note
In the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).
In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).
In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given).
Submitted Solution:
```
inputs = [int(x) for x in input().split()]
n, T = inputs[0], inputs[1]
songs = []
s = 0
songs_infos = {}
genres = {1: [], 2: [], 3: []}
i = 2
while i < len(inputs):
songs += [s]
songs_infos[s] = [inputs[i], inputs[i + 1]]
genres[songs_infos[s][1]] += [s]
i += 2
s += 1
``` | instruction | 0 | 56,470 | 24 | 112,940 |
No | output | 1 | 56,470 | 24 | 112,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | instruction | 0 | 57,332 | 24 | 114,664 |
Tags: greedy, two pointers
Correct Solution:
```
t = int(input())
for _ in range(t):
bb = input().split()
while bb == []:
bb = input().split()
k, n, m = int(bb[0]), int(bb[1]), int(bb[2])
s1 = input().split()
s2 = input().split()
for i in range(n):
s1[i] = int(s1[i])
for i in range(m):
s2[i] = int(s2[i])
l = 0
r = 0
out = []
flag = True
n,m=m,n
while l < m or r < n:
if l == m:
if s2[r] > k:
if s2[r] == 0:
out.append(s2[r])
r+=1
k+=1
else:
print(-1)
flag = False
break
elif s2[r] <= k:
out.append(s2[r])
if s2[r] == 0: k+=1
r +=1
elif r == n:
if s1[l] > k:
if s1[l] == 0:
out.append(s1[l])
l+=1
k+=1
else:
print(-1)
flag = False
break
elif s1[l] <= k:
out.append(s1[l])
if s1[l] == 0:
k+=1
l +=1
else:
if min(s1[l], s2[r]) > k:
maa = min(s1[l], s2[r])
if maa == 0:
out.append(maa)
if maa == s1[l]: l+=1
else: r+=1
k +=1
else:
print(-1)
flag = False
break
elif min(s1[l], s2[r]) <= k:
maa = min(s1[l], s2[r])
if maa == 0: k+=1
out.append(maa)
if maa == s1[l]:
l += 1
else:
r += 1
if flag == False: continue
print(*out)
``` | output | 1 | 57,332 | 24 | 114,665 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | instruction | 0 | 57,333 | 24 | 114,666 |
Tags: greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
tab = input()
k,n,m = map(int,input().split())
listn = list(map(int,input().split()))
listm = list(map(int,input().split()))
ans = []
status = True
stuck = False
noOfTries = 0
while(len(listm)>0 or len(listn)>0):
if noOfTries>3:
break
if(len(listn)==0):
status = False
noOfTries+=1
if(len(listm)==0):
status = True
noOfTries+=1
if(status and listn[0]!=0):
if(k>=listn[0]):
ans.append(listn[0])
listn = listn[1:]
noOfTries = 0
else:
status = False
noOfTries+=1
elif(status and listn[0]==0):
ans.append(listn[0])
listn = listn[1:]
noOfTries=0
k+=1
elif(not status and listm[0]!=0):
if(k>=listm[0]):
ans.append(listm[0])
listm = listm[1:]
noOfTries = 0
else:
status = True
noOfTries+=1
else:
ans.append(listm[0])
listm = listm[1:]
noOfTries = 0
k+=1
if(noOfTries>3):
print(-1)
else:
ans = list(map(str,ans))
print(" ".join(ans))
``` | output | 1 | 57,333 | 24 | 114,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | instruction | 0 | 57,334 | 24 | 114,668 |
Tags: greedy, two pointers
Correct Solution:
```
t = int(input())
for i in range(t):
a = input()
k, n, m = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
now = k
i=0
j=0
ans = []
while i<n or j<m:
if i!=n:
if a[i]==0:
k+=1
ans.append(0)
i+=1
continue
elif k>=a[i]:
ans.append(a[i])
i+=1
continue
if j!=m:
if b[j]==0:
k+=1
ans.append(0)
j+=1
continue
elif k>=b[j]:
ans.append(b[j])
j+=1
continue
break
if len(ans)< n+m:
print(-1)
else:
for i in range(n+m):
print(ans[i], end =' ')
print()
``` | output | 1 | 57,334 | 24 | 114,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | instruction | 0 | 57,335 | 24 | 114,670 |
Tags: greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
s=input()
k,n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ans=[]
i=0
j=0
flag=1
while(i<n and j<m):
if(a[i]==0):
ans.append(a[i])
i+=1
k+=1
elif(b[j]==0):
ans.append(b[j])
j+=1
k+=1
elif(a[i]<b[j]):
if(a[i]>k):
flag=0
break
else:
ans.append(a[i])
i+=1
else:
if(b[j]>k):
flag=0
break
else:
ans.append(b[j])
j+=1
if(i==n):
while(j<m):
if(b[j]>k):
flag=0
break
else:
if(b[j]==0):
k+=1
ans.append(b[j])
j+=1
else:
while(i<n):
if(a[i]>k):
flag=0
break
else:
ans.append(a[i])
if(a[i]==0):
k+=1
i+=1
if(flag):
print(*ans)
else:
print("-1")
``` | output | 1 | 57,335 | 24 | 114,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | instruction | 0 | 57,336 | 24 | 114,672 |
Tags: greedy, two pointers
Correct Solution:
```
def verify_result(k , arr):
for i in arr:
if i == 0:
k+=1
else:
if k >= i:
continue
else:
return [-1]
return arr
def solve():
input()
k,n,m = list(map(int , input().split()))
a = list(map(int , input().split()))
b = list(map(int , input().split()))
p1 = 0;
p2 = 0;
result = []
while p1<n or p2<m:
value_1 = float('inf')
value_2 = float('inf')
if p1<n:
value_1 = a[p1]
if value_1 == 0:
result.append(value_1)
p1 += 1
continue
if p2<m:
value_2 = b[p2]
if value_2 == 0:
result.append(value_2)
p2 += 1
continue
if value_1 < value_2:
result.append(value_1)
p1+=1
continue
else:
result.append(value_2)
p2 += 1
continue
print( *verify_result(k , result) , sep = ' ')
for i in range(int(input())):
solve()
``` | output | 1 | 57,336 | 24 | 114,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | instruction | 0 | 57,337 | 24 | 114,674 |
Tags: greedy, two pointers
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, 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)
MOD=10**9+7
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
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][0] >= key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
t=1
t=int(input())
for _ in range (t):
#n=int(input())
x=input()
k,n,m=map(int,input().split())
#a=list(map(int,input().split()))
#s=input()
#n=len(s)
a=list(map(int,input().split()))
b=list(map(int,input().split()))
i,j=0,0
res=[]
ch=1
line=k
for x in range (n+m):
if i<n and a[i]==0:
line+=1
i+=1
res.append(0)
elif j<m and b[j]==0:
line+=1
j+=1
res.append(0)
else:
if i<n and a[i]<=line:
res.append(a[i])
i+=1
elif j<m and b[j]<=line:
res.append(b[j])
j+=1
else:
res=[-1]
break
print(*res)
``` | output | 1 | 57,337 | 24 | 114,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | instruction | 0 | 57,338 | 24 | 114,676 |
Tags: greedy, two pointers
Correct Solution:
```
t = int(input())
for _ in range(t):
input()
k, n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
i, j = 0, 0
c = []
f = 1
while f == 1:
f = 0
while i < n and a[i] <= k:
c.append(a[i])
if a[i] == 0:
k += 1
i += 1
f = 1
while j < m and b[j] <= k:
c.append(b[j])
if b[j] == 0:
k += 1
j += 1
f = 1
if f == 0 and (i < n or j < m):
print(-1)
else:
print(*c)
``` | output | 1 | 57,338 | 24 | 114,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | instruction | 0 | 57,339 | 24 | 114,678 |
Tags: greedy, two pointers
Correct Solution:
```
import sys,math
from collections import deque,defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq
# sys.setrecursionlimit(10**6)
# OneDrive\Documents\codeforces
I=sys.stdin.readline
alpha="abcdefghijklmnopqrstuvwxyz"
mod=10**9 + 7
"""
x_move=[-1,0,1,0,-1,1,1,-1]
y_move=[0,1,0,-1,1,1,-1,-1]
"""
def ii():
return int(I().strip())
def li():
return list(map(int,I().strip().split()))
def mi():
return map(int,I().strip().split())
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom
def isPrime(n):
if n<=1:
return False
elif n<=2:
return True
else:
for i in range(2,int(n**.5)+1):
if n%i==0:
return False
return True
def main():
# ans=""
for _ in range(ii()):
I()
k,n,m=mi()
arr=li()
brr=li()
f=1
i=0
j=0
ans=[]
while i<n and j<m:
if arr[i]<=k:
ans.append(arr[i])
if arr[i]==0:
k+=1
i+=1
elif brr[j]<=k:
ans.append(brr[j])
if brr[j]==0:
k+=1
j+=1
else:
f=0
break
while i<n:
ans.append(arr[i])
if arr[i]>k:
f=0
break
elif arr[i]==0:
k+=1
i+=1
while j<m:
ans.append(brr[j])
if brr[j]>k:
f=0
break
elif brr[j]==0:
k+=1
j+=1
if f==0:
print(-1)
else:
print(*ans)
if __name__ == '__main__':
main()
``` | output | 1 | 57,339 | 24 | 114,679 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1
Submitted Solution:
```
def pair_programming(n,a,b):
res = []
i,j = 0,0
num = n
while i < len(a) and j < len(b):
if a[i] == 0 and b[j] == 0:
res.extend([0,0])
i += 1
j += 1
num += 2
elif a[i] == 0:
res.append(0)
num += 1
i += 1
elif b[j] == 0:
res.append(0)
num += 1
j += 1
else:
if a[i] < b[j]:
if a[i] <= num:
res.append(a[i])
i += 1
else:
return None
else:
if b[j] <= num:
res.append(b[j])
j += 1
else:
return None
idx, arr = None, None
if i == len(a):
idx = j
arr = b
else:
idx = i
arr = a
for i in range(idx,len(arr)):
if arr[i] == 0:
res.append(0)
num += 1
else:
if arr[i] <= num:
res.append(arr[i])
else:
return None
return res
N = int(input())
for _ in range(N):
input()
k = [int(s) for s in input().split()]
a = [int(s) for s in input().split()]
b = [int(s) for s in input().split()]
res = pair_programming(k[0],a,b)
if res:
print(*res)
else:
print(-1)
``` | instruction | 0 | 57,340 | 24 | 114,680 |
Yes | output | 1 | 57,340 | 24 | 114,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1
Submitted Solution:
```
# Problem: C. Pair Programming
# Contest: Codeforces - Codeforces Round #731 (Div. 3)
# URL: https://codeforces.com/contest/1547/problem/C
# Memory Limit: 512 MB
# Time Limit: 2000 ms
#
# Powered by CP Editor (https://cpeditor.org)
# ____ ____ ___ # skeon19
#| | / | | | |\ | #
#|____ |/ |___ | | | \ | # EON_KID
# | |\ | | | | \ | #
# ____| | \ ___ |____ |___| | \| # Soul_Silver
from collections import defaultdict
import sys,io,os
INP=sys.stdin.readline
inp=lambda:[*map(int,INP().encode().split())]
sinp=lambda:[*map(str,INP().split())]
out=sys.stdout.write
#from functools import reduce
#from bisect import bisect_right,bisect_left
#from sortedcontainers import SortedList, SortedSet, SortedDict
#import sympy #Prime number library
#import heapq
def main():
for _ in range(inp()[0]):
d=inp()
k,n,m=inp()
l=inp()
p=inp()
i=j=0
ans=[]
check=1
while i<n and j<m:
if l[i]==0:
ans.append(0)
k+=1
i+=1
elif p[j]==0:
ans.append(0)
k+=1
j+=1
else:
if l[i]>=p[j] and p[j]<=k:
ans.append(p[j])
j+=1
elif l[i]<=p[j] and l[i]<=k:
ans.append(l[i])
i+=1
else:
check=0
break
if not check:
break
if check:
while i<n:
if l[i]==0:
ans.append(0)
k+=1
i+=1
elif l[i]<=k:
ans.append(l[i])
i+=1
else:
check=0
break
while j<m:
if p[j]==0:
ans.append(0)
k+=1
j+=1
elif p[j]<=k:
ans.append(p[j])
j+=1
else:
check=0
break
if check:
print(*ans)
else:
print(-1)
else:
print(-1)
###############################################################
def SumOfExpOfFactors(a):
fac = 0
lis=SortedList()
if not a&1:
lis.add(2)
while not a&1:
a >>= 1
fac += 1
for i in range(3,int(a**0.5)+1,2):
if not a%i:
lis.add(i)
while not a%i:
a //= i
fac += 1
if a != 1:
lis.add(a)
fac += 1
return fac,lis
###############################################################
div=[0]*(1000001)
def NumOfDivisors(n): #O(nlog(n))
for i in range(1,n+1):
for j in range(i,n+1,i):
div[j]+=1
###############################################################
def primes1(n): #return a list having prime numbers from 2 to n
""" Returns a list of primes < n """
sieve = [True] * (n//2)
for i in range(3,int(n**0.5)+1,2):
if sieve[i//2]:
sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
return [2] + [2*i+1 for i in range(1,n//2) if sieve[i]]
##############################################################
def GCD(a,b):
if(b==0):
return a
else:
return GCD(b,a%b)
##############################################################
#
# 1
# / \
# 2 3
# /\ / \ \ \
#4 5 6 7 8 9
# \
# 10
class Graph:
def __init__(self):
self.Graph = defaultdict(list)
def addEdge(self, u, v):
self.Graph[u].append(v)
self.Graph[v].append(u)
#DFS Graph / tree
def DFSUtil(self, v, visited):
visited.add(v)
#print(v, end=' ')
for neighbour in self.Graph[v]:
if neighbour not in visited: #not needed if its a tree
self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set() #not needed if its a tree
self.DFSUtil(v, visited) #Visited not needed if its a tree
#BFS Graph / tree
def BFS(self, s):
# Mark all the vertices as not visited
visited = set()
# Create a queue for BFS
queue = []
queue.append(s)
visited.add(s)
while queue:
s = queue.pop(0)
#print (s, end = " ")
for i in self.Graph[s]:
if i not in visited:
queue.append(i)
visited.add(i)
'''
g = Graph()
g.addEdge(1, 2)
g.addEdge(1, 3)
g.addEdge(2, 4)
g.addEdge(2, 5)
g.addEdge(3, 6)
g.addEdge(3, 7)
g.addEdge(3, 8)
g.addEdge(3, 9)
g.addEdge(6,10)
g.DFS(1)
g.BFS(1) '''
##############################################################
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))
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
###################################################################################################
if __name__ == '__main__':
main()
``` | instruction | 0 | 57,341 | 24 | 114,682 |
Yes | output | 1 | 57,341 | 24 | 114,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1
Submitted Solution:
```
T = int(input())
for i in range(T):
input()
K,N,M = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
# standart_input
if A.count(0)+B.count(0)+K < max(A+B):
print(-1)
# Expection handling
else:
ans = []
l_A = 0
l_B = 0
for i in range(N+M):
# print(N,M,i,l_A,l_B,"A,B:",A[l_A:],B[l_B:])
if l_A < N and l_B < M:
if A[l_A] < B[l_B]:
ans.append(A[l_A])
l_A += 1
else:
ans.append(B[l_B])
l_B += 1
elif l_A < N:
ans.append(A[l_A])
l_A += 1
else:
ans.append(B[l_B])
l_B += 1
rows = K
f = True
# f is (ans == correct)
for j in range(N+M):
if ans[j] == 0:
rows += 1
elif ans[j] > rows:
f = False
if f:
print(*ans)
else:
print(-1)
``` | instruction | 0 | 57,342 | 24 | 114,684 |
Yes | output | 1 | 57,342 | 24 | 114,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1
Submitted Solution:
```
cases = int(input())
for _ in range(cases):
input()
k, n, m = map(int, input().split())
arr1 = list(map(int, input().split()))[::-1]
arr2 = list(map(int, input().split()))[::-1]
ans = []
cur_line = k
for i in range(n+m):
if arr1 and arr2:
if arr1[-1] <= arr2[-1]:
last = arr1.pop()
else:
last = arr2.pop()
elif arr1:
last = arr1.pop()
elif arr2:
last = arr2.pop()
if last > cur_line:
print(-1)
break
if last == 0:
cur_line += 1
ans.append(last)
else:
print(*ans)
``` | instruction | 0 | 57,343 | 24 | 114,686 |
Yes | output | 1 | 57,343 | 24 | 114,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1
Submitted Solution:
```
# DEFINING SOME GOOD STUFF
import heapq
import sys
from math import *
import threading
from heapq import *
from itertools import count
from pprint import pprint
from collections import defaultdict
'''
intialise defaultdict by any kind of value by default you want to take ( int -> 0 | list -> [] )
'''
from heapq import heapify, heappop, heappush
sys.setrecursionlimit(300000)
# threading.stack_size(10**8)
'''
-> if you are increasing recursionlimit then remember submitting using python3 rather pypy3
-> sometimes increasing stack size don't work locally but it will work on CF
'''
mod = 10 ** 9+7
inf = 10 ** 15
decision = ['NO', 'YES']
yes = 'YES'
no = 'NO'
# ------------------------------FASTIO----------------------------
import os
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 npr(n, r):
return (factorial(n)%mod) // (factorial(n-r)%mod) if n >= r else 0
def ncr(n, r):
return (factorial(n)%mod) // ((factorial(r)%mod) * (factorial(n-r)%mod)) if n >= r else 0
def lower_bound(li, num):
answer = -1
start = 0
end = len(li)-1
while (start <= end):
middle = (end+start) // 2
if li[middle] >= num:
answer = middle
end = middle-1
else:
start = middle+1
return answer # min index where x is not less than num
def upper_bound(li, num):
answer = -1
start = 0
end = len(li)-1
while (start <= end):
middle = (end+start) // 2
if li[middle] <= num:
answer = middle
start = middle+1
else:
end = middle-1
return answer # max index where x is not greater than num
def abs(x):
return x if x >= 0 else -x
def binary_search(li, val):
# print(lb, ub, li)
ans = -1
lb = 0
ub = len(li)-1
while (lb <= ub):
mid = (lb+ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid-1
elif val > li[mid]:
lb = mid+1
else:
ans = mid # return index
break
return ans
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1]+i)
return pref_sum
def SieveOfEratosthenes(n):
prime = [{1, i} for i in range(n+1)]
p = 2
while (p <= n):
for i in range(p * 2, n+1, p):
prime[i].add(p)
p += 1
return prime
def primefactors(n):
factors = []
while (n % 2 == 0):
factors.append(2)
n //= 2
for i in range(3, int(sqrt(n))+1, 2): # only odd factors left
while n % i == 0:
factors.append(i)
n //= i
if n > 2: # incase of prime
factors.append(n)
return factors
def prod(li):
ans = 1
for i in li:
ans *= i
return ans
def sumk(a, b):
print('called for', a, b)
ans = a * (a+1) // 2
ans -= b * (b+1) // 2
return ans
def sumi(n):
ans = 0
if len(n) > 1:
for x in n:
ans += int(x)
return ans
else:
return int(n)
def checkwin(x, a):
if a[0][0] == a[1][1] == a[2][2] == x:
return 1
if a[0][2] == a[1][1] == a[2][0] == x:
return 1
if (len(set(a[0])) == 1 and a[0][0] == x) or (len(set(a[1])) == 1 and a[1][0] == x) or (len(set(a[2])) == 1 and a[2][0] == x):
return 1
if (len(set(a[0][:])) == 1 and a[0][0] == x) or (len(set(a[1][:])) == 1 and a[0][1] == x) or (len(set(a[2][:])) == 1 and a[0][0] == x):
return 1
return 0
# _______________________________________________________________#
# def main():
karmanya = int(input())
# karmanya = 1
# divisors = SieveOfEratosthenes(200010)
# print(divisors)
while karmanya != 0:
karmanya -= 1
n = input()
k,n,m = map(int, input().split())
# a = [int(x) for x in list(input())]
a = list(map(int, input().split()))
b = list(map(int, input().split()))
# c = list(map(int, input().split()))
# d = defaultdict(list)
za,zb = a.count(0), a.count(0)
mxa, mxb = max(a), max(b)
if za + zb + k < max(mxa, mxb):
print(-1)
else:
ans = [0 for i in range(za + zb)]
for i in a:
if i != 0:
ans.append(i)
for i in b:
if i != 0:
ans.append(i)
print(*ans)
# t = threading.Thread(target=main)
# t.start()
# t.join()
``` | instruction | 0 | 57,344 | 24 | 114,688 |
No | output | 1 | 57,344 | 24 | 114,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1
Submitted Solution:
```
#DaRk DeveLopeR
import sys
#taking input as string
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
mod = 10**9+7; Mod = 998244353; INF = float('inf')
#______________________________________________________________________________________________________
import math
from bisect import *
from heapq import *
from collections import defaultdict as dd
from collections import OrderedDict as odict
from collections import Counter as cc
from collections import deque
from itertools import groupby
sys.setrecursionlimit(20*20*20*20+10) #this is must for dfs
def solve():
input()
k,n,m=takeivr()
arr1=takeiar()
arr2=takeiar()
arr=[]
count0=0
for i in arr1:
if i==0:
count0+=1
arr.append(i)
for i in arr2:
if i==0:
count0+=1
arr.append(i)
arr.sort()
k+=count0
for i in arr:
if i==0:
continue
elif i>k:
print(-1)
return
print(*arr)
return
def main():
global tt
if not ONLINE_JUDGE:
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
t = 1
t = takein()
#t = 1
for tt in range(1,t + 1):
solve()
if not ONLINE_JUDGE:
print("Time Elapsed :",time.time() - start_time,"seconds")
sys.stdout.close()
#---------------------- USER DEFINED INPUT FUNCTIONS ----------------------#
def takein():
return (int(sys.stdin.readline().rstrip("\r\n")))
# input the string
def takesr():
return (sys.stdin.readline().rstrip("\r\n"))
# input int array
def takeiar():
return (list(map(int, sys.stdin.readline().rstrip("\r\n").split())))
# input string array
def takesar():
return (list(map(str, sys.stdin.readline().rstrip("\r\n").split())))
# innut values for the diffrent variables
def takeivr():
return (map(int, sys.stdin.readline().rstrip("\r\n").split()))
def takesvr():
return (map(str, sys.stdin.readline().rstrip("\r\n").split()))
#------------------ USER DEFINED PROGRAMMING FUNCTIONS ------------------#
def ispalindrome(s):
return s==s[::-1]
def invert(bit_s):
# convert binary string
# into integer
temp = int(bit_s, 2)
# applying Ex-or operator
# b/w 10 and 31
inverse_s = temp ^ (2 ** (len(bit_s) + 1) - 1)
# convert the integer result
# into binary result and then
# slicing of the '0b1'
# binary indicator
rslt = bin(inverse_s)[3 : ]
return str(rslt)
def counter(a):
q = [0] * max(a)
for i in range(len(a)):
q[a[i] - 1] = q[a[i] - 1] + 1
return(q)
def counter_elements(a):
q = dict()
for i in range(len(a)):
if a[i] not in q:
q[a[i]] = 0
q[a[i]] = q[a[i]] + 1
return(q)
def string_counter(a):
q = [0] * 26
for i in range(len(a)):
q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
return(q)
def factorial(n,m = 1000000007):
q = 1
for i in range(n):
q = (q * (i + 1)) % m
return(q)
def factors(n):
q = []
for i in range(1,int(n ** 0.5) + 1):
if n % i == 0: q.append(i); q.append(n // i)
return(list(sorted(list(set(q)))))
def prime_factors(n):
q = []
while n % 2 == 0: q.append(2); n = n // 2
for i in range(3,int(n ** 0.5) + 1,2):
while n % i == 0: q.append(i); n = n // i
if n > 2: q.append(n)
return(list(sorted(q)))
def transpose(a):
n,m = len(a),len(a[0])
b = [[0] * n for i in range(m)]
for i in range(m):
for j in range(n):
b[i][j] = a[j][i]
return(b)
def power_two(x):
return (x and (not(x & (x - 1))))
def ceil(a, b):
return -(-a // b)
def seive(n):
a = [1]
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p ** 2,n + 1, p):
prime[i] = False
p = p + 1
for p in range(2,n + 1):
if prime[p]:
a.append(p)
return(a)
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1]+i)
return pref_sum
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def binary_search(li, val):
# print(lb, ub, li)
ans = -1
lb = 0
ub = len(li)-1
while (lb <= ub):
mid = (lb+ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid-1
elif val > li[mid]:
lb = mid+1
else:
ans = mid # return index
break
return ans
def upper_bound(li, num):
answer = -1
start = 0
end = len(li)-1
while (start <= end):
middle = (end+start) // 2
if li[middle] <= num:
answer = middle
start = middle+1
else:
end = middle-1
return answer # max index where x is not greater than num
def lower_bound(li, num):
answer = -1
start = 0
end = len(li)-1
while (start <= end):
middle = (end+start) // 2
if li[middle] >= num:
answer = middle
end = middle-1
else:
start = middle+1
return answer # min index where x is not less than num
#-----------------------------------------------------------------------#
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
input = sys.stdin.readline
main()
``` | instruction | 0 | 57,345 | 24 | 114,690 |
No | output | 1 | 57,345 | 24 | 114,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1
Submitted Solution:
```
# Problem: C. Pair Programming
# Contest: Codeforces - Codeforces Round #731 (Div. 3)
# URL: https://codeforces.com/contest/1547/problem/C
# Memory Limit: 512 MB
# Time Limit: 2000 ms
#
# Powered by CP Editor (https://cpeditor.org)
# ____ ____ ___ # skeon19
#| | / | | | |\ | #
#|____ |/ |___ | | | \ | # EON_KID
# | |\ | | | | \ | #
# ____| | \ ___ |____ |___| | \| # Soul_Silver
from collections import defaultdict
import sys,io,os
INP=sys.stdin.readline
inp=lambda:[*map(int,INP().encode().split())]
sinp=lambda:[*map(str,INP().split())]
out=sys.stdout.write
#from functools import reduce
#from bisect import bisect_right,bisect_left
#from sortedcontainers import SortedList, SortedSet, SortedDict
#import sympy #Prime number library
#import heapq
def main():
for _ in range(inp()[0]):
d=inp()
k,n,m=inp()
l=inp()
p=inp()
i=j=0
ans=[]
check=1
while i<n and j<m:
if l[i]==0 and p[j]!=0:
ans.append(0)
k+=1
i+=1
elif p[j]==0 and l[i]!=0:
ans.append(0)
k+=1
j+=1
else:
if l[i]>=p[j] and p[j]<=k:
ans.append(p[j])
j+=1
elif l[i]<=p[j] and l[i]<=k:
ans.append(l[i])
i+=1
else:
check=0
break
if not check:
break
if check:
while i<n:
if l[i]==0:
ans.append(0)
k+=1
i+=1
elif l[i]<=k:
ans.append(l[i])
i+=1
else:
check=0
break
while j<m:
if p[j]==0:
ans.append(0)
k+=1
j+=1
elif p[j]<=k:
ans.append(p[j])
j+=1
else:
check=0
break
if check:
print(*ans)
else:
print(-1)
else:
print(-1)
###############################################################
def SumOfExpOfFactors(a):
fac = 0
lis=SortedList()
if not a&1:
lis.add(2)
while not a&1:
a >>= 1
fac += 1
for i in range(3,int(a**0.5)+1,2):
if not a%i:
lis.add(i)
while not a%i:
a //= i
fac += 1
if a != 1:
lis.add(a)
fac += 1
return fac,lis
###############################################################
div=[0]*(1000001)
def NumOfDivisors(n): #O(nlog(n))
for i in range(1,n+1):
for j in range(i,n+1,i):
div[j]+=1
###############################################################
def primes1(n): #return a list having prime numbers from 2 to n
""" Returns a list of primes < n """
sieve = [True] * (n//2)
for i in range(3,int(n**0.5)+1,2):
if sieve[i//2]:
sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
return [2] + [2*i+1 for i in range(1,n//2) if sieve[i]]
##############################################################
def GCD(a,b):
if(b==0):
return a
else:
return GCD(b,a%b)
##############################################################
#
# 1
# / \
# 2 3
# /\ / \ \ \
#4 5 6 7 8 9
# \
# 10
class Graph:
def __init__(self):
self.Graph = defaultdict(list)
def addEdge(self, u, v):
self.Graph[u].append(v)
self.Graph[v].append(u)
#DFS Graph / tree
def DFSUtil(self, v, visited):
visited.add(v)
#print(v, end=' ')
for neighbour in self.Graph[v]:
if neighbour not in visited: #not needed if its a tree
self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set() #not needed if its a tree
self.DFSUtil(v, visited) #Visited not needed if its a tree
#BFS Graph / tree
def BFS(self, s):
# Mark all the vertices as not visited
visited = set()
# Create a queue for BFS
queue = []
queue.append(s)
visited.add(s)
while queue:
s = queue.pop(0)
#print (s, end = " ")
for i in self.Graph[s]:
if i not in visited:
queue.append(i)
visited.add(i)
'''
g = Graph()
g.addEdge(1, 2)
g.addEdge(1, 3)
g.addEdge(2, 4)
g.addEdge(2, 5)
g.addEdge(3, 6)
g.addEdge(3, 7)
g.addEdge(3, 8)
g.addEdge(3, 9)
g.addEdge(6,10)
g.DFS(1)
g.BFS(1) '''
##############################################################
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))
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
###################################################################################################
if __name__ == '__main__':
main()
``` | instruction | 0 | 57,346 | 24 | 114,692 |
No | output | 1 | 57,346 | 24 | 114,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1
Submitted Solution:
```
import math
inp=int(input())
for _ in range(inp):
input()
k,n,m=map(int,input().split(" "))
nl=list(map(int,input().split(" ")))
ml=list(map(int,input().split(" ")))
final=nl+ml
final.sort()
flag=True
d=k
for i in final:
if i==0:
d+=1
else:
if d<i:
flag=False
break
if flag:
q=[]
while 0 in final:
q.append(final.pop(0))
res=[]
print(*res)
else:
print(-1)
# from wrapt_timeout_decorator import *
# @timeout(2.5)
# def i():
# p=0
# try:
# i()
# except Exception:
# print("TLE")
``` | instruction | 0 | 57,347 | 24 | 114,694 |
No | output | 1 | 57,347 | 24 | 114,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | instruction | 0 | 57,571 | 24 | 115,142 |
Tags: implementation
Correct Solution:
```
online = set()
answer = 0
try:
while True:
line = input()
if line[0] == '+' or line[0] == '-':
name = line[1:]
if line[0] == '+':
online.add(name)
else:
online.remove(name)
else:
answer += len(line.split(':')[1]) * len(online)
except:
pass
print(answer)
``` | output | 1 | 57,571 | 24 | 115,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | instruction | 0 | 57,572 | 24 | 115,144 |
Tags: implementation
Correct Solution:
```
c=0
l=[]
x=0
while x==0:
try:
s=input()
if "+" in s and s[1:] not in l:
l.append(s[1:])
if "-" in s and s[1:] in l:
l.remove(s[1:])
if ":" in s:
a,m=s.split(":")
c+=len(m)*len(l)
except:
x=1
print(c)
``` | output | 1 | 57,572 | 24 | 115,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | instruction | 0 | 57,573 | 24 | 115,146 |
Tags: implementation
Correct Solution:
```
import sys
people,bits = 0,0
for i in sys.stdin:
if i[0] == "+": people += 1;
elif i[0] == "-": people -= 1
else: bits += people*(len(i)-i.find(":")-2)
print(bits)
``` | output | 1 | 57,573 | 24 | 115,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | instruction | 0 | 57,574 | 24 | 115,148 |
Tags: implementation
Correct Solution:
```
# @author: guoyc
# @date: 2018/7/20
res = 0
n = 0
import sys
for s in sys.stdin:
if s[0] == '+':
n += 1
elif s[0] == '-':
n -= 1
elif s.find(':') != -1:
name, msg = s.split(':')
res += n * (len(msg)-1)
print(res)
``` | output | 1 | 57,574 | 24 | 115,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | instruction | 0 | 57,575 | 24 | 115,150 |
Tags: implementation
Correct Solution:
```
"""f = open("input.txt", "r")
if f.mode == 'r':
contents = f.readlines()
"""
import sys
contents = []
participants = 0
sum = 0
while True:
try:
s = input()
contents.append(s)
except:
break
for content in contents:
if content[0] == "+":
participants += 1
elif content[0] == "-":
participants -= 1
else:
flash = ":"
message = content.partition(flash)[2]
message = message.rstrip('\n')
traffic = len(message)
traffic *= participants
sum += traffic
print(sum)
``` | output | 1 | 57,575 | 24 | 115,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | instruction | 0 | 57,576 | 24 | 115,152 |
Tags: implementation
Correct Solution:
```
names = []
res = 0
while True:
try:
s = input()
except:
break
if s[0] == '+':
names.append(s[1:])
elif s[0] == '-':
names.remove(s[1:])
else:
if ':' in s:
length = len(s.split(':')[1])
res = res + length * len(names)
else:
break
print(res)
``` | output | 1 | 57,576 | 24 | 115,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | instruction | 0 | 57,577 | 24 | 115,154 |
Tags: implementation
Correct Solution:
```
d = set()
count = 0
try:
while(1):
s = input()
if(s.startswith("+")):
d.add(s[1:])
elif(s.startswith("-")):
d.remove(s[1:])
else:
count += len(s.split(":")[-1]) * len(d)
except:
pass
print(count)
``` | output | 1 | 57,577 | 24 | 115,155 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | instruction | 0 | 57,578 | 24 | 115,156 |
Tags: implementation
Correct Solution:
```
guys = set()
res = 0
while 1:
try:
curRequest = input()
except:
break
if curRequest[0] == '+':
guys.add(curRequest[1:])
elif curRequest[0] == '-':
guys.remove(curRequest[1:])
else:
proReq = curRequest[curRequest.find(':') + 1:]
# print(proReq)
res += len(proReq)*len(guys)
print(res)
``` | output | 1 | 57,578 | 24 | 115,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Submitted Solution:
```
import sys
trafic = 0
s = set()
for request in sys.__stdin__:
if request[0] == "+":
s.add(request[1:])
elif request[0] == "-":
s.remove(request[1:])
else:
trafic += len(request[request.find(":")+1:-1])*len(s)
print(trafic)
``` | instruction | 0 | 57,579 | 24 | 115,158 |
Yes | output | 1 | 57,579 | 24 | 115,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Submitted Solution:
```
import sys
users = list()
ans = 0
for line in sys.stdin:
line = line.rstrip()
if line[0] == '+':
users.append(line[1:])
elif line[0] == '-':
users.remove(line[1:])
else:
msg = line[line.index(':') + 1:]
ans += len(msg) * len(users)
print(ans)
``` | instruction | 0 | 57,580 | 24 | 115,160 |
Yes | output | 1 | 57,580 | 24 | 115,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Submitted Solution:
```
import sys
a = b = 0
for m in sys.stdin:
a += m[0] == '+'
a -= m[0] == '-'
b += (':' in m)*(len(m) - m.find(':') - 2) * a
print(b)
``` | instruction | 0 | 57,581 | 24 | 115,162 |
Yes | output | 1 | 57,581 | 24 | 115,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Submitted Solution:
```
import sys
nums=ans=0
for s in sys.stdin:
jj=s[0]
if jj=='+':
nums+=1
elif jj=='-':
nums-=1
else:
n,t=s.split(':')
ans+=(len(t)-1)*nums
print(ans)
``` | instruction | 0 | 57,582 | 24 | 115,164 |
Yes | output | 1 | 57,582 | 24 | 115,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Submitted Solution:
```
import sys
k=0
s=0
for line in sys.stdin:
print(line[0])
if line[0]=='+':
k+=1
if line[0]=='-':
k-=1
if line[0]!='+' and line[0]!='-':
s+=len(line)-line.index(':')
print(s)
``` | instruction | 0 | 57,583 | 24 | 115,166 |
No | output | 1 | 57,583 | 24 | 115,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Submitted Solution:
```
# @author: guoyc
# @date: 2018/7/20
res = 0
n = 0
import sys
for s in sys.stdin:
if s[0] == '+':
n += 1
elif s[0] == '-':
n -= 1
else:
name, msg = s.split(':')
res += n * (len(msg)-2)
print(res)
# import sys
#
# z = x = 0
# for s in sys.stdin:
# if s[0] == '+':
# x += 1
# elif s[0] == '-':
# x -= 1
# else:
# z += (len(s) - s.find(':') - 2) * x
# print(z)
``` | instruction | 0 | 57,584 | 24 | 115,168 |
No | output | 1 | 57,584 | 24 | 115,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Submitted Solution:
```
import sys
serverTraffic = 0
activeUsers = 0
for line in sys.stdin:
if line[0] == '+':
activeUsers += 1
elif line[0] == '-':
activeUsers -= 1
else:
serverTraffic += (activeUsers - 1) * (len(line) - line.find(':') - 1)
#serverTraffic += activeUsers * (len(line) - line.find(':') - 2)
print(serverTraffic)
``` | instruction | 0 | 57,585 | 24 | 115,170 |
No | output | 1 | 57,585 | 24 | 115,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14
Submitted Solution:
```
import sys
users = []
ans = 0
for s in sys.stdin:
if s[0] == "+":
users.append(s[1:])
elif s[0] == "-":
del users[users.index(s[1:])]
else:
ans += len(users)*len(s[s.index(":")+1:])
print(ans)
``` | instruction | 0 | 57,586 | 24 | 115,172 |
No | output | 1 | 57,586 | 24 | 115,173 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.
Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai ββmay be unknown. Such values are represented by number -1.
For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values ββ-1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values ββ-1 may correspond to an arbitrary positive integer and the values ai > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.
Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·105) β the number of elements in the sequence. The second line contains integer values a1, a2, ..., an separated by a space (1 β€ ai β€ 109 or ai = - 1).
Output
Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.
Examples
Input
9
8 6 4 2 1 4 7 10 2
Output
3
Input
9
-1 6 -1 2 -1 4 7 -1 2
Output
3
Input
5
-1 -1 -1 -1 -1
Output
1
Input
7
-1 -1 4 5 1 2 3
Output
2 | instruction | 0 | 58,371 | 24 | 116,742 |
Tags: greedy, implementation, math
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
i = 0
ans = 0
while i < n:
ans += 1
i1 = i
while i1 < n and a[i1] == -1:
i1 += 1
if i1 == n:
break
i2 = i1 + 1
while i2 < n and a[i2] == -1:
i2 += 1
if i2 == n:
break
dist = i2 - i1
step = (a[i2] - a[i1]) // dist
if (a[i2] - a[i1]) % dist != 0 or (step > 0 and a[i1] - (i1 - i) * step <= 0):
i = i2
continue
i3 = i2 + 1
while i3 < n:
nxt = a[i2] + step * (i3 - i2)
if nxt <= 0 or (a[i3] != -1 and a[i3] != nxt):
break
i3 += 1
i = i3
print(ans)
``` | output | 1 | 58,371 | 24 | 116,743 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.
Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai ββmay be unknown. Such values are represented by number -1.
For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values ββ-1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values ββ-1 may correspond to an arbitrary positive integer and the values ai > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.
Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·105) β the number of elements in the sequence. The second line contains integer values a1, a2, ..., an separated by a space (1 β€ ai β€ 109 or ai = - 1).
Output
Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.
Examples
Input
9
8 6 4 2 1 4 7 10 2
Output
3
Input
9
-1 6 -1 2 -1 4 7 -1 2
Output
3
Input
5
-1 -1 -1 -1 -1
Output
1
Input
7
-1 -1 4 5 1 2 3
Output
2 | instruction | 0 | 58,372 | 24 | 116,744 |
Tags: greedy, implementation, math
Correct Solution:
```
import sys
import math
n = int(sys.stdin.readline())
if n <= 2:
print(1)
sys.exit(0)
a = [int(s) for s in sys.stdin.readline().split()]
st = -1 # index of first positive number in current subset of a
ed = -1 # index last positive number in current subset of a
# differation is (a[ed] - a[st])/(ed - st)
leading_zeros = 0 # -1 before a[st]
seg_count = 1
for (i, v) in enumerate(a):
if v == -1:
if st == -1:
leading_zeros += 1
else:
if ed != -1:
# check if v should be a non-positive number
if a[ed] + (i-ed) * (a[ed] - a[st])/(ed-st) <= 0:
st = -1
ed = -1
leading_zeros = 1
seg_count += 1
else:
pass
else:
pass
else:
if st == -1:
st = i # find first positive number
else:
if ed == -1:
ed = i
#print(i)
if (v - a[st]) % (i-st) != 0 or a[st] - (v-a[st])/(i-st) * leading_zeros <= 0:
# a[st..i] can't be an arithmetic progression
st = i
ed = -1
seg_count += 1
leading_zeros = 0
else:
ed = i
else:
if (v-a[ed])%(i-ed) != 0 or (v-a[ed]) * (ed - st) != (a[ed] - a[st]) * (i-ed):
st = i
ed = -1
seg_count += 1
leading_zeros = 0
else:
ed = i #leave ed the first positive number after a[st] is also ok
#print( "[" +str(st) + " " + str(ed) + "] " + str(seg_count) + " " + str(leading_zeros) )
print(seg_count)
``` | output | 1 | 58,372 | 24 | 116,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.
Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai ββmay be unknown. Such values are represented by number -1.
For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values ββ-1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values ββ-1 may correspond to an arbitrary positive integer and the values ai > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.
Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·105) β the number of elements in the sequence. The second line contains integer values a1, a2, ..., an separated by a space (1 β€ ai β€ 109 or ai = - 1).
Output
Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.
Examples
Input
9
8 6 4 2 1 4 7 10 2
Output
3
Input
9
-1 6 -1 2 -1 4 7 -1 2
Output
3
Input
5
-1 -1 -1 -1 -1
Output
1
Input
7
-1 -1 4 5 1 2 3
Output
2
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
i = 0
while i < len(a) and a[i] == -1:
i += 1
j = i + 1
while j < len(a) and a[j] == -1:
j += 1
if j >= len(a):
print(1)
exit()
ans = 1
m = j + 1
if (a[j] - a[i]) % (j - i) != 0 or a[i] - (a[j] - a[i]) / (j - i) * i <= 0:
i, j = j, -1
ans += 1
for k in range(m, len(a)):
if a[k] == -1:
continue
if j == -1 and (a[k] - a[i]) % (k - i) == 0 or j != -1 and (a[k] - a[j]) * (j - i) == (a[j] - a[i]) * (k - j):
j = k
else:
i = k
ans += 1
print(ans)
``` | instruction | 0 | 58,373 | 24 | 116,746 |
No | output | 1 | 58,373 | 24 | 116,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.
Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai ββmay be unknown. Such values are represented by number -1.
For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values ββ-1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values ββ-1 may correspond to an arbitrary positive integer and the values ai > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.
Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·105) β the number of elements in the sequence. The second line contains integer values a1, a2, ..., an separated by a space (1 β€ ai β€ 109 or ai = - 1).
Output
Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.
Examples
Input
9
8 6 4 2 1 4 7 10 2
Output
3
Input
9
-1 6 -1 2 -1 4 7 -1 2
Output
3
Input
5
-1 -1 -1 -1 -1
Output
1
Input
7
-1 -1 4 5 1 2 3
Output
2
Submitted Solution:
```
"""
Codeforces Round 241 Div 1 Problem D
Author : chaotic_iak
Language: Python 3.3.4
"""
class InputHandlerObject(object):
inputs = []
def getInput(self, n = 0):
res = ""
inputs = self.inputs
if not inputs: inputs.extend(input().split(" "))
if n == 0:
res = inputs[:]
inputs[:] = []
while n > len(inputs):
inputs.extend(input().split(" "))
if n > 0:
res = inputs[:n]
inputs[:n] = []
return res
InputHandler = InputHandlerObject()
g = InputHandler.getInput
############################## SOLUTION ##############################
n = int(input().strip())
q = [int(x) for x in g()]
diffs = []
indices = []
ct = 0
stillstart = True
for i in range(len(q)):
if q[i] == 0: q[i] = -1 # because it's easier to type 0 than -1
if q[i] == -1 and stillstart: continue
if stillstart:
stillstart = False
ct = 1
indices.append(i)
continue
if q[i] == -1:
ct += 1
else:
d = q[i] - q[i-ct]
if d % ct:
diffs.append("X")
else:
diffs.append(d//ct)
indices.append(i)
ct = 1
if not diffs:
print(1)
else:
res = 1
if diffs[0] != "X" and q[indices[0]] - diffs[0] * indices[0] <= 0:
res += 1
diffs.pop(0)
indices.pop(0)
prevok = False
for i in range(len(diffs)):
if diffs[i] == "X":
res += 1
notenough = False
if 0 < i < len(diffs)-1:
if diffs[i-1] != "X" and diffs[i+1] != "X":
leftmx = n if diffs[i-1] >= 0 else (- q[indices[i]] // diffs[i-1] + indices[i])
if diffs[i-1] < 0 and not q[indices[i]] % diffs[i-1]: leftmx -= 1
rightmn = 0 if diffs[i+1] <= 0 else (- q[indices[i+1]] // diffs[i+1] + indices[i+1])
if diffs[i+1] > 0 and not q[indices[i+1]] % diffs[i+1]: rightmn += 1
if leftmx + 1 < rightmn: notenough = True
if notenough:
res += 1
prevok = False
continue
if prevok and diffs[i-1] == diffs[i]:
continue
if prevok:
res += 1
notenough = False
if 0 < i < len(diffs)-1:
if diffs[i-1] != "X" and diffs[i+1] != "X":
leftmx = n if diffs[i-1] >= 0 else (- q[indices[i]] // diffs[i-1] + indices[i])
if diffs[i-1] < 0 and not q[indices[i]] % diffs[i-1]: leftmx -= 1
rightmn = 0 if diffs[i+1] <= 0 else (- q[indices[i+1]] // diffs[i+1] + indices[i+1])
if diffs[i+1] > 0 and not q[indices[i+1]] % diffs[i+1]: rightmn += 1
if leftmx + 1 < rightmn: notenough = True
if notenough:
passed = True
if i > 1:
i -= 1
if diffs[i-1] != "X" and diffs[i+1] != "X":
leftmx = n if diffs[i-1] >= 0 else (- q[indices[i]] // diffs[i-1] + indices[i])
if diffs[i-1] < 0 and not q[indices[i]] % diffs[i-1]: leftmx -= 1
rightmn = 0 if diffs[i+1] <= 0 else (- q[indices[i+1]] // diffs[i+1] + indices[i+1])
if diffs[i+1] > 0 and not q[indices[i+1]] % diffs[i+1]: rightmn += 1
if leftmx + 1 < rightmn: notenough = True
i += 1
if i < len(diffs) - 2:
i += 1
if diffs[i-1] != "X" and diffs[i+1] != "X":
leftmx = n if diffs[i-1] >= 0 else (- q[indices[i]] // diffs[i-1] + indices[i])
if diffs[i-1] < 0 and not q[indices[i]] % diffs[i-1]: leftmx -= 1
rightmn = 0 if diffs[i+1] <= 0 else (- q[indices[i+1]] // diffs[i+1] + indices[i+1])
if diffs[i+1] > 0 and not q[indices[i+1]] % diffs[i+1]: rightmn += 1
if leftmx + 1 < rightmn: notenough = True
i -= 1
if not passed:
res += 1
prevok = False
else:
prevok = True
else:
prevok = False
continue
if not prevok:
prevok = True
if prevok and diffs[-1] != "X" and q[indices[-1]] + diffs[-1] * (n-1 - indices[-1]) <= 0: res += 1
print(res)
``` | instruction | 0 | 58,374 | 24 | 116,748 |
No | output | 1 | 58,374 | 24 | 116,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.
Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai ββmay be unknown. Such values are represented by number -1.
For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values ββ-1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values ββ-1 may correspond to an arbitrary positive integer and the values ai > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.
Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·105) β the number of elements in the sequence. The second line contains integer values a1, a2, ..., an separated by a space (1 β€ ai β€ 109 or ai = - 1).
Output
Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.
Examples
Input
9
8 6 4 2 1 4 7 10 2
Output
3
Input
9
-1 6 -1 2 -1 4 7 -1 2
Output
3
Input
5
-1 -1 -1 -1 -1
Output
1
Input
7
-1 -1 4 5 1 2 3
Output
2
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
i = 0
while i < len(a) and a[i] == -1:
i += 1
j = i + 1
while j < len(a) and a[j] == -1:
j += 1
if j >= len(a):
print(1)
exit()
ans = 1
m = j + 1
if (a[j] - a[i]) % (j - i) != 0 or a[i] - (a[j] - a[i]) / (j - i) * i <= 0:
i, j = j, -1
ans += 1
for k in range(m, len(a)):
if a[k] == -1:
continue
if j == -1 and (a[k] - a[i]) % (k - i) == 0 or j != -1 and (a[k] - a[j]) * (j - i) == (a[j] - a[i]) * (k - j):
j = k
else:
i, j = k, -1
ans += 1
print(ans)
``` | instruction | 0 | 58,375 | 24 | 116,750 |
No | output | 1 | 58,375 | 24 | 116,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.
Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai ββmay be unknown. Such values are represented by number -1.
For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values ββ-1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values ββ-1 may correspond to an arbitrary positive integer and the values ai > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.
Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
Input
The first line of the input contains integer n (1 β€ n β€ 2Β·105) β the number of elements in the sequence. The second line contains integer values a1, a2, ..., an separated by a space (1 β€ ai β€ 109 or ai = - 1).
Output
Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.
Examples
Input
9
8 6 4 2 1 4 7 10 2
Output
3
Input
9
-1 6 -1 2 -1 4 7 -1 2
Output
3
Input
5
-1 -1 -1 -1 -1
Output
1
Input
7
-1 -1 4 5 1 2 3
Output
2
Submitted Solution:
```
n=int(input())
A=list(map(int,input().split()))
P=[]
for i in range(n):
if(A[i]!=-1):
P.append((A[i],i))
if(len(P)==0 or len(P)==1):
print(1)
else:
p=10**10
d=10**10
z=10**10
start=0
for i in range(n):
if(A[i]==-1):
if(d==10**10):
continue
else:
A[i]=A[i-1]+d
if(A[i]<0):
A[i]=-1
d=10**10
start=i
else:
if(d==10**10):
if(p==10**10):
p=A[i]
z=i
else:
D=A[i]-p
if(D%(i-z)==0):
for k in range(i-1,z,-1):
A[k]=A[k+1]-(D//(i-z))
r=False
for k in range(z-1,start-1,-1):
if(r==False):
A[k]=A[k+1]-(D//(i-z))
if(A[k]<=0):
A[k]=1
r=True
else:
A[k]=1
d=D//(i-z)
else:
for k in range(start,i):
A[k]=p
start=i
d=10**10
p=A[i]
z=i
else:
x=A[i]-A[i-1]
if(x==d):
continue
else:
z=i
start=i
p=A[i]
d=10**10
if(A[-1]==-1):
for k in range(start,n):
A[k]=10
d=A[1]-A[0]
ans=1
i=2
while(i<n):
if(A[i]-A[i-1]==d):
i+=1
continue
else:
ans+=1
if(i==n-1):
break
i+=1
d=A[i]-A[i-1]
i+=1
print(ans)
``` | instruction | 0 | 58,376 | 24 | 116,752 |
No | output | 1 | 58,376 | 24 | 116,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i.
Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if n=6 and a=[3, 9, 4, 6, 7, 5], then the number of days with a bad price is 3 β these are days 2 (a_2=9), 4 (a_4=6) and 5 (a_5=7).
Print the number of days with a bad price.
You have to answer t independent data sets.
Input
The first line contains an integer t (1 β€ t β€ 10000) β the number of sets of input data in the test. Input data sets must be processed independently, one after another.
Each input data set consists of two lines. The first line contains an integer n (1 β€ n β€ 150000) β the number of days. The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^6), where a_i is the price on the i-th day.
It is guaranteed that the sum of n over all data sets in the test does not exceed 150000.
Output
Print t integers, the j-th of which should be equal to the number of days with a bad price in the j-th input data set.
Example
Input
5
6
3 9 4 6 7 5
1
1000000
2
2 1
10
31 41 59 26 53 58 97 93 23 84
7
3 2 1 2 3 4 5
Output
3
0
1
8
2 | instruction | 0 | 58,914 | 24 | 117,828 |
Tags: data structures, implementation
Correct Solution:
```
# Sourav
from sys import stdin
def solve(n,arr):
k,ctr = 9999999999,0
for j in range(n):
k = min (k,arr[n-j-1])
if(k < arr[n-j-1]):
ctr += 1
return ctr
t = int(stdin.readline().rstrip())
for i in range(t):
n = int(stdin.readline().rstrip())
arr = [int(x) for x in stdin.readline().rstrip().split()]
print(solve(n,arr))
``` | output | 1 | 58,914 | 24 | 117,829 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.