message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48. | instruction | 0 | 106,322 | 14 | 212,644 |
Tags: dp, greedy, sortings, two pointers
Correct Solution:
```
N, D, M = map(int, input().split())
A = sorted(map(int, input().split()), reverse=True)
L = [a for a in A if a>M]
S = [a for a in A if a<=M]
cum_S = [0]
c = 0
for s in S:
c += s
cum_S.append(c)
d = N-1
ans = max(A)
if len(L) == 0:
print(sum(S))
exit()
cum_L = 0
for n, l in enumerate(L, 1):
cum_L += l
if d < 0:
break
need = (n-1)*D
if not len(L) - n <= need:
if len(L) - n <= need + D:
need = len(L) - n
else:
d -= D+1
continue
n_s = need - (len(L) - n)
#print(n_s)
an = cum_S[max(0, len(S)-n_s)] + cum_L
#print(n, an, need)
ans = max(ans, an)
d -= D+1
print(ans)
``` | output | 1 | 106,322 | 14 | 212,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48. | instruction | 0 | 106,323 | 14 | 212,646 |
Tags: dp, greedy, sortings, two pointers
Correct Solution:
```
from sys import stdin
import sys
n,d,m = map(int,stdin.readline().split())
a = list(map(int,stdin.readline().split()))
a.sort()
a.reverse()
over = [0]
below = [0]
nuse = 0
for i in range(n):
if a[i] > m:
over.append(over[-1] + a[i])
else:
below.append(below[-1] + a[i])
ans = 0
#ans = over[min( len(over)-1 , (n+d) // (d+1) )]
if len(over) == 1:
print (below[-1])
sys.exit()
#left
for l in range(n+1):
r = n - l
if l > len(below)-1:
break
if r < len(over)-1 or (len(over)-1) * (d+1) < r:
continue
ans = max(ans , below[l] + over[(r+d)//(d+1)])
print (ans)
``` | output | 1 | 106,323 | 14 | 212,647 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48. | instruction | 0 | 106,324 | 14 | 212,648 |
Tags: dp, greedy, sortings, two pointers
Correct Solution:
```
import sys
import math,bisect
from collections import defaultdict
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,OrderedDict
#input = iter(sys.stdin.buffer.read().decode().splitlines())._next_
def neo(): return map(int,input().split())
def Neo(): return list(map(int,input().split()))
n,d,m = neo()
A = Neo()
G,L = [],[]
for i in A:
if i > m:
G.append(i)
else:
L.append(i)
G.sort(reverse = True)
L.sort()
Gpf = list(accumulate(G))
Lpf = list(accumulate(L))
Gpf = [0]+Gpf
Lpf = [0]+Lpf
Ans = []
for i in range(len(Gpf)):
days = (i-1)*(d+1)+1
if days <= n:
t = Gpf[i]
rd = n - days
t += Lpf[-1] - Lpf[max(0,len(Lpf)-rd-1)]
Ans.append(t)
print(max(Ans))
``` | output | 1 | 106,324 | 14 | 212,649 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48. | instruction | 0 | 106,325 | 14 | 212,650 |
Tags: dp, greedy, sortings, two pointers
Correct Solution:
```
n,d,m=map(int,input().split())
a=list(map(int,input().split()))
e,f=[i for i in a if i<=m],[i for i in a if i>m]
e.sort(reverse=True)
f.sort(reverse=True)
c=len(e)
if c==n:
print(sum(a))
exit()
l=1
r=min((n-1)//(d+1)+1,len(f))
#k's range
#e,f 's sum
ans=sum(e)
nowe,nowf=0,0
#print(l,r)
#print(n-(1+(l-1)*(d+1)),l)
#print(e,f)
#print(l,r)
#print(e)
#print(f)
for i in range(l,r+1):
if i==l:
nowe=sum(e[:n-(1+(l-1)*(d+1))])
nowf=sum(f[:l])
ans=max(nowe+nowf,ans)
continue
nowe-=sum(e[n-(1+(i-1)*(d+1)):n-(1+(i-1-1)*(d+1))])
nowf+=f[i-1]
ans=max(nowe+nowf,ans)
print(ans)
``` | output | 1 | 106,325 | 14 | 212,651 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48. | instruction | 0 | 106,326 | 14 | 212,652 |
Tags: dp, greedy, sortings, two pointers
Correct Solution:
```
n, d, m = map(int, input().split())
a = list(map(int, input().split()))
small, big = [], []
for i in a:
if i > m:
big.append(i)
else:
small.append(i)
small.sort(reverse=True)
big.sort(reverse=True)
res = 0
if len(small) == 0:
cnt = int((n + d) / (d + 1))
for i in range(cnt):
res += big[i]
elif len(big) == 0:
res = 0
for i in range(n):
res += small[i]
else:
sum = [small[0]]
for i in range(1, len(small)):
sum.append(sum[i - 1] + small[i])
tot = 0
for i in range(len(big)):
tot += big[i]
rem = min(n - (i * (d + 1) + 1), len(sum))
if rem == 0:
res = max(res, tot)
elif rem > 0:
res = max(res, tot + sum[rem - 1])
else:
break
print(res)
``` | output | 1 | 106,326 | 14 | 212,653 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48. | instruction | 0 | 106,327 | 14 | 212,654 |
Tags: dp, greedy, sortings, two pointers
Correct Solution:
```
# TestCases
# 5 2 11
# 8 10 15 23 5
# # 48
# 20 2 16
# 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
# # 195
from math import ceil
import sys
read = lambda: sys.stdin.readline().rstrip("\r\n")
def maxFun():
n, d, m = map(int, read().split())
nums = list(map(int, read().split()))
nums.sort(reverse = True)
smaller = list()
larger = list()
for i in nums:
if i <= m:
smaller.append(i)
else:
larger.append(i)
large_len = len(larger)
smaller = smaller + [0] * (n - len(smaller))
larger = larger + [0] * (n - len(larger))
large_suff = [0] * (n+1)
small_pre = [0] * (n+1)
for i in range(1, n+1):
small_pre[i] = small_pre[i - 1] + smaller[i-1]
large_suff[i] = large_suff[i - 1] + larger[i-1]
# print(small_pre)
# print(large_suff)
ans = small_pre[-1]
for j in range(1, large_len + 1):
pos = (j - 1) * (d + 1) + 1
if pos > n:
break
ans = max(ans, large_suff[j] + small_pre[n - pos])
print(ans)
if __name__ == "__main__":
maxFun()
``` | output | 1 | 106,327 | 14 | 212,655 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48. | instruction | 0 | 106,328 | 14 | 212,656 |
Tags: dp, greedy, sortings, two pointers
Correct Solution:
```
def solve(n, d, m, a):
a.sort()
small = sorted(x for x in a if x <= m)
scs = [0]
for x in small:
scs.append(scs[-1] + x)
sol = scs[-1]
bn = n - len(small)
take, r, sbig, possible = 1, n-1, 0, True
while possible:
skip = d*(take-1)
if a[r] > m and skip + take <= n:
sbig += a[r]
skip = max(skip - (bn - take), 0)
ssmall = scs[-1] - scs[skip] if skip < len(scs) else 0
sol = max(sol, sbig + ssmall)
r -= 1
take += 1
else:
possible = False
return sol
# 1 2 2 2 4 5 5 6 7 8 13 16 16 16 16 16 17 18 20 21
n, d, m = map(int, input().split())
a = list(map(int, input().split()))
print(solve(n, d, m, a))
``` | output | 1 | 106,328 | 14 | 212,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
Submitted Solution:
```
def solve():
n, d, m = map(int, input().split());a = list(map(int, input().split()));f = list();g = list()
for x in a:
if x > m:f.append(x)
else:g.append(x)
f.sort(reverse=True);g.sort(reverse=True);ng = len(g);a = [0] * (ng + 1)
for i in range(ng):a[i+1] = a[i] + g[i]
ans = a[ng];cur = 0
for i in range(len(f)):
if i + 1 + i * d > n: break
cur += f[i];v = n - i * d - i - 1
if v > ng: v = ng
if v < 0: v = 0
if ans < cur + a[v]:ans = cur + a[v]
print(ans)
return
solve()
``` | instruction | 0 | 106,329 | 14 | 212,658 |
Yes | output | 1 | 106,329 | 14 | 212,659 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
Submitted Solution:
```
'''
Author: nuoyanli
Date: 2020-08-12 22:26:14
LastEditTime: 2020-08-13 00:22:36
Author's blog: https://blog.nuoyanli.com/
Description: Plum blossom from the bitter cold!
'''
import sys
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
n,d,m =nm()
a = nl()
num = 0
for i in range(n):
num+=(a[i]<=m)
a.sort()
a.insert(0,0)
su = []
su.append(0)
for i in range(1,n+1):
su.append(su[i-1]+ a[i])
div ,ans = n-num,0
d+=1
for i in range(0,div+1):
if i*d>=div and (i-1)*d<=n-1:
temp = n-max((i-1)*d+1,div)
ans = max(ans,su[n]-su[n-i]+su[num]-su[num-temp])
print(ans)
``` | instruction | 0 | 106,330 | 14 | 212,660 |
Yes | output | 1 | 106,330 | 14 | 212,661 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
Submitted Solution:
```
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
# from sys import stdin
# input = stdin.readline
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,6)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
def pmat(A):
for ele in A:
print(ele,end="\n")
n, d, m = map(int, input().split())
arr = list(map(int, input().split()))
dp = [0]*(n+1)
arr.sort()
count = 0
for i in range(n):
dp[i+1] = arr[i] + dp[i]
if arr[i] <= m:
count += 1
res = dp[count]
for i in range(1, n-count+1):
if (i-1)*d + i > n:
break
res = max(res, dp[n]-dp[n-i]+dp[count]-dp[max(0, (i-1)*d-(n-count-i))])
print(res)
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
``` | instruction | 0 | 106,331 | 14 | 212,662 |
Yes | output | 1 | 106,331 | 14 | 212,663 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, d, m = map(int,input().split())
A = list(map(int,input().split()))
from random import randint
# for ii in range(100):
# n = 7
# d = 5
# m = 1
# A = [randint(1, 20) for i in range(n)]
# A = [3, 18, 7, 19, 7, 18, 2]
B = []
C = []
for i in range(n):
if A[i] > m:
B.append(A[i])
else:
C.append(A[i])
B.sort(reverse=True)
C.sort(reverse=True)
# print(B,C)
ans = 0
if len(B) == 0:
ans = sum(A)
else:
bmin = (n-len(C)-1) // (d+1) + 1
bmax = min(len(B), (n-1)//(d+1) + 1)
bind = bmin
cind = n-((bmin-1)*(d+1)+1) - 1
ans0 = sum(B[:bmin])
ans0 += sum(C[:cind+1])
ans = ans0
# print(bind,cind,ans0)
for i in range(cind-len(C)+1):
C.append(0)
while bind < bmax:
ans0 += B[bind]
bind += 1
for i in range(d+1):
if len(C) > 0 and cind >= 0:
# print(cind)
ans0 -= C[cind]
cind -= 1
ans = max(ans0, ans)
# print(bind,cind,ans0)
print(ans)
# import itertools
# D = list(itertools.permutations([i for i in range(n)]))
# ans1 = 0
# for i in range(len(D)):
# ans2 = 0
# mu = 0
# for j in range(n):
# if mu == 0:
# ans2 += A[D[i][j]]
# if A[D[i][j]] > m:
# mu = d
# else:
# mu -= 1
# ans1 = max(ans1,ans2)
# if ans!=ans1:
# print(ans,ans1,A)
``` | instruction | 0 | 106,332 | 14 | 212,664 |
Yes | output | 1 | 106,332 | 14 | 212,665 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
Submitted Solution:
```
#Bhargey Mehta (Junior)
#DA-IICT, Gandhinagar
import sys, math
mod = 10**9 + 7
def solve(test_index):
n, d, m = map(int, input().split())
a, b = [], []
for x in map(int, input().split()):
if x <= m: a.append(x)
else: b.append(x)
a = sorted(a, reverse=True)
b = sorted(b, reverse=True)
if len(b) == 0:
print(sum(a))
return
else:
ans = sum(a) + b[0]
for i in range(1, len(a)):
a[i] += a[i-1]
for i in range(1, len(b)):
b[i] += b[i-1]
for blocks in range(1, len(b)):
use = len(a) - blocks * d
if use < 0: continue
elif use == 0: smallSum = 0
else: smallSum = a[use-1]
bigSum = b[blocks]
ans = max(ans, smallSum + bigSum)
print(ans)
return
if 'PyPy' not in sys.version:
sys.stdin = open('input.txt', 'r')
sys.setrecursionlimit(100000)
num_tests = 1
#num_tests = int(input())
for test in range(1, num_tests+1):
#print("Case #{}: ".format(test), end="")
solve(test)
``` | instruction | 0 | 106,333 | 14 | 212,666 |
No | output | 1 | 106,333 | 14 | 212,667 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
Submitted Solution:
```
import sys
import math
input=sys.stdin.readline
n,d,m=map(int,input().split())
a=[int(i) for i in input().split() if i!='\n']
a.sort()
lo=-1
for i in range(n):
if a[i]>m:
lo=i
break
pref=[0]
for i in range(n):
pref.append(pref[-1]+a[i])
if n<=(d+1):
print(pref[lo])
else:
ans=0
if (n-1)%(d+1)==0:
pq=math.ceil((n-1)/(d+1))+1
else:
pq=math.ceil((n-1)/(d+1))
pos=min(n-lo,pq)
hi=n-pos
for i in range(hi,n):
ans+=a[i]
lo-=1
for i in range((pos-1)*(d+1),n-1):
ans+=a[lo]
lo-=1
lo+=1
if m==31335:
print(ans)
while True:
if lo<0 or hi>=n:
break
if (pref[lo]-pref[max(0,lo-d-1)])>a[hi]:
ans-=a[hi]
ans+=(pref[lo]-pref[max(0,lo-d-1)])
lo-=(d+1)
hi+=1
else:
break
print(ans)
``` | instruction | 0 | 106,334 | 14 | 212,668 |
No | output | 1 | 106,334 | 14 | 212,669 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
Submitted Solution:
```
import sys
import math
input=sys.stdin.readline
n,d,m=map(int,input().split())
a=[int(i) for i in input().split() if i!='\n']
a.sort()
lo=-1
for i in range(n):
if a[i]>m:
lo=i
break
pref=[0]
for i in range(n):
pref.append(pref[-1]+a[i])
if n<=(d+1):
print(pref[lo])
else:
ans=0
if (n-1)%(d+1)==0:
pq=math.ceil((n-1)/(d+1))+1
else:
pq=math.ceil((n-1)/(d+1))
pos=min(n-lo,pq)
hi=n-pos
for i in range(hi,n):
ans+=a[i]
lo-=1
if d==31335:
print(ans,a[lo])
for i in range((pos-1)*(d+1),n-1):
if lo<0:
break
ans+=a[lo]
lo-=1
lo+=1
if d==31335:
print(hi,(pos-1)*(d+1))
while True:
if lo<0 or hi>=n:
break
if (pref[lo]-pref[max(0,lo-d-1)])>a[hi]:
ans-=a[hi]
ans+=(pref[lo]-pref[max(0,lo-d-1)])
lo-=(d+1)
hi+=1
else:
break
print(ans)
``` | instruction | 0 | 106,335 | 14 | 212,670 |
No | output | 1 | 106,335 | 14 | 212,671 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood.
* Otherwise, Du won't do anything.
Boboniu's mood is a constant m. On the i-th day:
* If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days.
* Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of a.
Input
The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9).
The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9).
Output
Print one integer: the maximum total fun factor among all permutations of a.
Examples
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
Note
In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be:
1. Make fun of Boboniu with fun factor 15.
2. Be muzzled.
3. Be muzzled.
4. Make fun of Boboniu with fun factor 10.
5. Make fun of Boboniu with fun factor 23.
Thus the total fun factor is 48.
Submitted Solution:
```
import sys
import math
input=sys.stdin.readline
n,d,m=map(int,input().split())
a=[int(i) for i in input().split() if i!='\n']
a.sort()
lo=-1
for i in range(n):
if a[i]>m:
lo=i
break
pref=[0]
for i in range(n):
pref.append(pref[-1]+a[i])
if n<=(d+1):
print(pref[lo])
else:
ans=0
if (n-1)%(d+1)==0:
pq=math.ceil((n-1)/(d+1))+1
else:
pq=math.ceil((n-1)/(d+1))
pos=min(n-lo,pq)
hi=n-pos
for i in range(hi,n):
ans+=a[i]
lo-=1
for i in range((pos-1)*(d+1),n-1):
ans+=a[lo]
lo-=1
lo+=1
if d==31335:
print(ans)
while True:
if lo<0 or hi>=n:
break
if (pref[lo]-pref[max(0,lo-d-1)])>a[hi]:
ans-=a[hi]
ans+=(pref[lo]-pref[max(0,lo-d-1)])
lo-=(d+1)
hi+=1
else:
break
print(ans)
``` | instruction | 0 | 106,336 | 14 | 212,672 |
No | output | 1 | 106,336 | 14 | 212,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter. | instruction | 0 | 106,444 | 14 | 212,888 |
Tags: greedy, implementation, sortings
Correct Solution:
```
import sys
import math
n, m, k = [int(x) for x in (sys.stdin.readline()).split()]
an = [int(x) for x in (sys.stdin.readline()).split()]
an.sort(reverse = True)
res = 0
i = 0
while(m > k):
if(i < n):
k -= 1
k += an[i]
i += 1
else:
break
res += 1
if(m <= k):
print(res)
else:
print(-1)
``` | output | 1 | 106,444 | 14 | 212,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter. | instruction | 0 | 106,445 | 14 | 212,890 |
Tags: greedy, implementation, sortings
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
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")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=-10**6, 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(50001)]
pp=[]
def SieveOfEratosthenes(n=50000):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for i in range(50001):
if prime[i]:
pp.append(i)
#---------------------------------running code------------------------------------------
n,m,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort(reverse=True)
if k>=m:
print(0)
else:
curr=k
count=0
for i in range (n):
curr+=a[i]-1
count+=1
if curr>=m:
break
if curr>=m:
print(count)
else:
print(-1)
``` | output | 1 | 106,445 | 14 | 212,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter. | instruction | 0 | 106,446 | 14 | 212,892 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n,m,k=map(int,input().split())
l = list(map(int,input().split()))
l.sort(reverse=True)
# l.reverse()
# print(l)
if m<=k:
print(0)
quit()
for ii,c in enumerate(l):
k+=c-1
# print(k)
if k>=m:
print('{}'.format(ii+1))
quit()
print(-1)
``` | output | 1 | 106,446 | 14 | 212,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter. | instruction | 0 | 106,447 | 14 | 212,894 |
Tags: greedy, implementation, sortings
Correct Solution:
```
def sockets():
n, m, k = map(int, input().split())
a = map(int, input().split())
a = sorted(a, reverse=True)
if m <= k:
print(0)
return
i = 0
for x in a:
k += x - 1
i += 1
if m <= k:
print(i)
return
print(-1)
sockets()
``` | output | 1 | 106,447 | 14 | 212,895 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter. | instruction | 0 | 106,448 | 14 | 212,896 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n, m, k = list(map(int, input().rstrip().split()))
a = list(map(int, input().rstrip().split()))
a.sort(reverse=True)
if m <= k:
print(0)
else:
ans = 0
x = m
while (True):
maxm = a.pop(0)
m = m - maxm
k = k - 1
ans += 1
if k >= m:
print(ans)
break
elif ans == n:
print(-1)
break
``` | output | 1 | 106,448 | 14 | 212,897 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter. | instruction | 0 | 106,449 | 14 | 212,898 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n,m,k=map(int,input().split())
l=list(map(int,input().split()))
l.sort(reverse=True)
if(m<k):
print("0")
else:
c=k
i=0
j=0
flag=0
while(c<m):
if(i==n):
flag=1
break
c=c-1
c=c+l[i]
i=i+1
j=j+1
if(flag==1):
print("-1")
else:
print(j)
``` | output | 1 | 106,449 | 14 | 212,899 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter. | instruction | 0 | 106,450 | 14 | 212,900 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n,m,k=map(int,input().split())
arr=list(map(int,input().split()))
arr.sort()
arr=arr+[k]
ans=0
s=0
while ans<n+1:
s+=arr[-ans-1]
if s>=m:
break
ans+=1
s-=1
if s>=m:
print(ans)
else:
print("-1")
``` | output | 1 | 106,450 | 14 | 212,901 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets.
Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity.
What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter.
Input
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter.
Output
Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1.
Examples
Input
3 5 3
3 1 2
Output
1
Input
4 7 2
3 3 2 4
Output
2
Input
5 5 1
1 3 1 2 1
Output
-1
Note
In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices.
One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter. | instruction | 0 | 106,451 | 14 | 212,902 |
Tags: greedy, implementation, sortings
Correct Solution:
```
import math
import os
import random
import re
import sys
import functools
from operator import itemgetter, attrgetter
if __name__ == '__main__':
n, m, k = list(map(int, input().strip().split()))
a, b, i = list(map(int, input().strip().split())), 0, 0
a.sort(reverse=True)
if m <= k:
print(b)
else:
while i < len(a):
if m <= k:
break
if k > 0:
k -= 1
elif m > 0:
m += 1
m -= a[i]
b += 1
i += 1
print("-1" if m > k else "{}".format(b))
``` | output | 1 | 106,451 | 14 | 212,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image> | instruction | 0 | 106,558 | 14 | 213,116 |
Tags: dsu, implementation
Correct Solution:
```
s1,s2,d,v = set(),set(),{},[]
for _ in range(int(input())):
a,b = map(int,input().split())
d[a]=b;s1.add(a);s2.add(b)
v.append(list(s1-s2)[0]);v.append(d[0])
while 1:
try:v.append(d[v[-2]]);v.append(d[v[-2]])
except:v.pop();print(*v);break
``` | output | 1 | 106,558 | 14 | 213,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image> | instruction | 0 | 106,559 | 14 | 213,118 |
Tags: dsu, implementation
Correct Solution:
```
n=int(input());
a=[];
ab=1000002*[-1];
b=1000002*[0];
res=[0,0]
for i in range(n):
[aa,bb]=[int(i) for i in input().split()];
a.append(aa);
ab[aa]=bb;
b[bb]=1;
if(aa==0):
res[1]=bb;
for i in a:
if b[i]==0:
res[0]=i;
for i in range(2,n):
res.append(ab[res[i-2]]);
print(*res,sep=' ');
``` | output | 1 | 106,559 | 14 | 213,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image> | instruction | 0 | 106,560 | 14 | 213,120 |
Tags: dsu, implementation
Correct Solution:
```
from sys import stdin, stdout
fin = stdin
fout = stdout
n = int(fin.readline().rstrip())
q = []
d = dict()
a = dict()
for i in range(n):
q.append(list(map(int, fin.readline().split())))
a[q[i][0]] = q[i][1]
if q[i][0] not in d:
d[q[i][0]] = 0
d[q[i][0]] += 1
if q[i][1] not in d:
d[q[i][1]] = 0
d[q[i][1]] += 1
ans = [0, 0]
for key in d.keys():
if d[key] == 1:
for i in range(n):
if key == q[i][0]:
ans[0] = key
if 0 == q[i][0]:
ans[1] = q[i][1]
fout.write(' '.join(map(str, (ans[0], ans[1]))))
for i in range(2, n):
ans.append(a[ans[i - 2]])
fout.write(' ' + str(a[ans[i - 2]]))
``` | output | 1 | 106,560 | 14 | 213,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image> | instruction | 0 | 106,561 | 14 | 213,122 |
Tags: dsu, implementation
Correct Solution:
```
ab = {}
ba = {}
n = int(input())
res = [None]*n
for _ in range(n):
a, b = input().split()
ab[a], ba[b] = b, a
z = "0"
for i in range(1, n, 2):
res[i] = z = ab[z]
if n&1:#=1
n += 1
for x in ba:
if x not in ab:
ba["0"] = x
break
z = "0"
for i in range(n-2, -1, -2):
res[i] = z = ba[z]
print(*res)
``` | output | 1 | 106,561 | 14 | 213,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image> | instruction | 0 | 106,562 | 14 | 213,124 |
Tags: dsu, implementation
Correct Solution:
```
from sys import stdin
n = int(input())
graph = {}
for _ in range(1, n + 1):
ai, bi = input().split()
graph[ai] = bi
ans = [0] * n
ans[0] = (set(graph.keys()) - set(graph.values())).pop()
ans[1] = graph['0']
for i in range(2, n):
ans[i] = graph[ans[i - 2]]
print(*ans)
``` | output | 1 | 106,562 | 14 | 213,125 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image> | instruction | 0 | 106,563 | 14 | 213,126 |
Tags: dsu, implementation
Correct Solution:
```
n=int(input())
d={}
t={}
for i in range(n):
Qi,Pi=list(map(int,input().split()))
d[Qi]=Pi
t[Pi]=Qi
ans = [list(filter(lambda x:t.get(x)==None,d.keys()))[0],d.get(0)]
for i in range(2,n):
ans.append(d.get(ans[i-2]))
print(*ans)
``` | output | 1 | 106,563 | 14 | 213,127 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image> | instruction | 0 | 106,564 | 14 | 213,128 |
Tags: dsu, implementation
Correct Solution:
```
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import insort, bisect_right, bisect_left
import threading, sys
def main():
n = int(input())
adj, rdj = {}, {}
ans = [0]*n
for i in range(n):
a, b = map(int, input().split())
adj[a] = b
rdj[b] = a
done, st, ind = {},0,1
while ind < n:
st = adj[st]
ans[ind] = st
done[st] = 1
ind += 2
st, ind = 0, n-2
while ind >= 0:
st = rdj[st]
ans[ind] = st
ind -= 2
if n%2:
nd = 0
for k in adj:
if k not in done and k != 0: nd = k; break
while nd in rdj: nd = rdj[nd]
for i in range(n):
if ans[i] == 0:
ans[i] = nd
nd = adj.get(nd,0)
print(" ".join(map(str,ans)))
if __name__ == "__main__":
"""sys.setrecursionlimit(400000)
threading.stack_size(40960000)"""
thread = threading.Thread(target=main)
thread.start()
``` | output | 1 | 106,564 | 14 | 213,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image> | instruction | 0 | 106,565 | 14 | 213,130 |
Tags: dsu, implementation
Correct Solution:
```
n = int(input())
d1 = dict()
d2 = dict()
ar = [0] * (30000000)
for i in range(n):
a, b = map(int, input().split())
ar[a] += 1
ar[b] += 1
d1[a] = b
d2[b] = a
if n % 2 == 0:
x = 0
ar1 = []
ar2 = []
while x in d1:
ar1.append(d1[x])
x = d1[x]
x = 0
while x in d2:
ar2.append(d2[x])
x = d2[x]
ar2 = list(reversed(ar2))
for i in range(len(ar2)):
print(ar2[i], end = ' ')
print(ar1[i], end = ' ')
else:
arx = []
for i in range(1000000):
if ar[i] == 1:
arx.append(i)
a = arx[0]
b = arx[1]
if b in d2:# a in d2
a, b = b, a
x = 0
ar1 = []
ar2 = []
while x in d1:
if d1[x] != 0:
ar1.append(d1[x])
x = d1[x]
if x == 0:
break
x = a
while x in d2:
ar2.append(d2[x])
x = d2[x]
ar2 = list(reversed(ar2))
for i in range(len(ar2)):
print(ar2[i], end = ' ')
print(ar1[i], end = ' ')
print(a)
``` | output | 1 | 106,565 | 14 | 213,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
Submitted Solution:
```
x=int(input())
left=dict()
lset=set()
rset=set()
q=[0]*x
i=0
while i<x:
l=[int(j) for j in input().split()]
left[l[0]]=l[1]
lset.add(l[0])
rset.add(l[1])
i+=1
i=lset.difference(rset).pop()
j=0
q[0]=i
k=1
while k<x:
q[k]=left[j]
k+=1
if k<x:
q[k]=left[i]
k+=1
i=left[i]
j=left[j]
print(" ".join([str(k) for k in q]))
``` | instruction | 0 | 106,566 | 14 | 213,132 |
Yes | output | 1 | 106,566 | 14 | 213,133 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
Submitted Solution:
```
n = int(input())
dic = {}
for i in range(n):
(a,b) = [int(j) for j in input().split(' ')]
dic[a] = b
ans = []
ans.append(0)
val = set(dic.values())
# print(val)
for key in dic.keys():
if(key not in val):
ans.append(key)
break
for i in range(n-1):
ans.append(dic[ans[-2]])
ans = [str(i) for i in ans]
print(' '.join(ans[1:]))
``` | instruction | 0 | 106,567 | 14 | 213,134 |
Yes | output | 1 | 106,567 | 14 | 213,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
Submitted Solution:
```
readints=lambda:map(int, input().strip('\n').split())
n=int(input())
def printlist(lst):
buf=''
for i in range(len(lst)-1):
buf+=(str(lst[i])+' ')
buf+=str(lst[-1])
print(buf)
def findFirstStudent(students):
behindSet=set()
for front,behind in students:
behindSet.add(behind)
for front,_ in students:
if front not in behindSet:
return front
def reconstructLine(students):
n=len(students)
line=[0]*n
frontToBehind={}
for front,behind in students:
frontToBehind[front]=behind
line[0]=findFirstStudent(students)
line[1]=frontToBehind[0]
for i in range(2,n):
line[i]=frontToBehind[line[i-2]]
return line
students=[tuple(readints()) for _ in range(n)]
printlist(reconstructLine(students))
``` | instruction | 0 | 106,568 | 14 | 213,136 |
Yes | output | 1 | 106,568 | 14 | 213,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
Submitted Solution:
```
n = int(input())
seq = dict()
result = [0] * n
time = dict()
length = n
for i in range(n):
tem = [int(i) for i in input().split()]
seq[tem[0]] = tem[1]
if tem[0] not in time:
time[tem[0]] = 1
else:
time[tem[0]] = 2
if tem[1] not in time:
time[tem[1]] = 0
else:
time[tem[1]] = 2
for item in time:
if time[item] == 1:
result[0] = item
k = item
j = seq[0]
result[1] = j
bound = n // 2 + 1
if n > 2:
for i in range(1, bound):
result[2*i] = seq[k]
k = seq[k]
if seq[j] == 0:
break
result[2*i+1] = seq[j]
j = seq[j]
if seq[k] == 0:
break
for m in range(0, len(result)):
print(result[m], end = ' ')
``` | instruction | 0 | 106,569 | 14 | 213,138 |
Yes | output | 1 | 106,569 | 14 | 213,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
Submitted Solution:
```
import sys
import math
from collections import defaultdict
import itertools
MAXNUM = math.inf
MINNUM = -1 * math.inf
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
sys.stdout.write() # add to me
pass
def solve():
pass
def readinput():
students = int(sys.stdin.readline().rstrip())
idNumbers = {}
singles = set()
for _ in range(students):
prev, nxt = getInts()
if prev not in idNumbers:
singles.add(prev)
idNumbers[prev] = [0, nxt]
else:
singles.remove(prev)
idNumbers[prev][1] = nxt
if nxt not in idNumbers:
idNumbers[nxt] = [prev, 0]
singles.add(nxt)
else:
singles.remove(nxt)
idNumbers[nxt][0] = prev
ans = list(singles)
if idNumbers[ans[0]][0] == 0:
start = ans[0]
else:
start = ans[1]
second = idNumbers[0][1]
ans = []
ans.append(start)
ans.append(second)
cur1 = start
cur2 = second
while idNumbers[cur1][1] != 0 or idNumbers[cur2][1] != 0:
if idNumbers[cur1][1] != 0:
cur1 = idNumbers[cur1][1]
ans.append(cur1)
if idNumbers[cur2][1] != 0:
cur2 = idNumbers[cur2][1]
ans.append(cur2)
if len(idNumbers) == 3:
ans = [idNumbers[0][1], idNumbers[0][0]]
for ele in ans:
print(ele, end=" ")
readinput()
``` | instruction | 0 | 106,570 | 14 | 213,140 |
No | output | 1 | 106,570 | 14 | 213,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
Submitted Solution:
```
a=int(input())
#a1=a//2+1
d={}
#t=[]
dinv={}
for i in range(a):
b1=input().split()
b=list(b1)
d[int(b[0])]=int(b[1]) #так мы создали словарик со всеми данными
# t+=[int(b[1])]
dinv[int(b[1])] = int(b[0])
c1=[]
n=0
#n=d.get(0)
#c1+=[n]
for i in range(a):
n=d.get(n) # d[n]
if n in d:
c1 += [n]
#if n in d.values():
# c1+=[n] // создали первый список из всех четных студентов
else:
break
#print(c1)
c2=[]
for i in d.keys():
if i not in dinv and i!=0:
k=i
c2+=[k] #// нашли начало второго списка
for i in range(a):
k=d.get(k)
if k in dinv:
c2+=[k] #// создали второй список (нечетные)
else:
break
#print(c1)
#print(c2)
c1+=[0]
c2+=[0]
for i in range(a):
if c2[i]!=0:
print(c2[i], end=' ')
if c1[i]!=0:
print(c1[i], end=' ')
else:
break
``` | instruction | 0 | 106,571 | 14 | 213,142 |
No | output | 1 | 106,571 | 14 | 213,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
Submitted Solution:
```
a=int(input())
a1=a//2+1
d={}
t=[]
dinv={}
for i in range(a):
b1=input().split()
b=list(b1)
d[int(b[0])]=int(b[1]) #так мы создали словарик со всеми данными
# t+=[int(b[1])]
dinv[int(b[1])] = int(b[0])
c1=[]
n=0
#n=d.get(0)
#c1+=[n]
for i in range(a1):
n=d.get(n) # d[n]
if n in d:
c1 += [n]
#if n in d.values():
# c1+=[n] // создали первый список из всех четных студентов
#else:
# break
#print(c1)
c2=[]
for i in d.keys():
if i not in dinv and i!=0:
k=i
c2+=[k] #// нашли начало второго списка
for i in range(a1+1):
k=d.get(k)
if k in dinv:
c2+=[k] #// создали второй список (нечетные)
# else:
# break
#print(c1)
#print(c2)
c1+=[0]
c2+=[0]
for i in range(a):
if c2[i]!=0:
print(c2[i], end=' ')
if c1[i]!=0:
print(c1[i], end=' ')
else:
break
``` | instruction | 0 | 106,572 | 14 | 213,144 |
No | output | 1 | 106,572 | 14 | 213,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
Output
Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
Examples
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
Note
The picture illustrates the queue for the first sample.
<image>
Submitted Solution:
```
n=int(input())
lis=[]
for i in range(n):
lis.append(input().split())
lis0=[0 for k in range(n)]
lis1=[]
lis2=[]
for i in range(n):
lis1.append(lis[i][0])
lis2.append(lis[i][1])
print(lis1,lis2)
for k in lis1:
if k not in lis2:
lis0[0]=k
lis0[1]=lis2[lis1.index('0')]
for i in range(2,n):
lis0[i]=lis2[lis1.index(lis0[i-2])]
print(lis0)
print(' '.join(lis0))
``` | instruction | 0 | 106,573 | 14 | 213,146 |
No | output | 1 | 106,573 | 14 | 213,147 |
Provide a correct Python 3 solution for this coding contest problem.
Haruna is a high school student. She must remember the seating arrangements in her class because she is a class president. It is too difficult task to remember if there are so many students.
That is the reason why seating rearrangement is depress task for her. But students have a complaint if seating is fixed.
One day, she made a rule that all students must move but they don't move so far as the result of seating rearrangement.
The following is the rule. The class room consists of r*c seats. Each r row has c seats. The coordinate of the front row and most left is (1,1). The last row and right most is (r,c). After seating rearrangement, all students must move next to their seat. If a student sit (y,x) before seating arrangement, his/her seat must be (y,x+1) , (y,x-1), (y+1,x) or (y-1,x). The new seat must be inside of the class room. For example (0,1) or (r+1,c) is not allowed.
Your task is to check whether it is possible to rearrange seats based on the above rule.
Hint
For the second case, before seat rearrangement, the state is shown as follows.
1 2
3 4
There are some possible arrangements. For example
2 4
1 3
or
2 1
4 3
is valid arrangement.
Input
Input consists of multiple datasets. Each dataset consists of 2 integers. The last input contains two 0. A dataset is given by the following format.
r c
Input satisfies the following constraint.
1 ≤ r ≤ 19, 1 ≤ c ≤ 19
Output
Print "yes" without quates in one line if it is possible to rearrange the seats, otherwise print "no" without quates in one line.
Example
Input
1 1
2 2
0 0
Output
no
yes | instruction | 0 | 106,969 | 14 | 213,938 |
"Correct Solution:
```
while 1:
a,b=map(int,input().split())
if a==b==0: break
if a*b%2: print("no")
else: print("yes")
``` | output | 1 | 106,969 | 14 | 213,939 |
Provide a correct Python 3 solution for this coding contest problem.
Haruna is a high school student. She must remember the seating arrangements in her class because she is a class president. It is too difficult task to remember if there are so many students.
That is the reason why seating rearrangement is depress task for her. But students have a complaint if seating is fixed.
One day, she made a rule that all students must move but they don't move so far as the result of seating rearrangement.
The following is the rule. The class room consists of r*c seats. Each r row has c seats. The coordinate of the front row and most left is (1,1). The last row and right most is (r,c). After seating rearrangement, all students must move next to their seat. If a student sit (y,x) before seating arrangement, his/her seat must be (y,x+1) , (y,x-1), (y+1,x) or (y-1,x). The new seat must be inside of the class room. For example (0,1) or (r+1,c) is not allowed.
Your task is to check whether it is possible to rearrange seats based on the above rule.
Hint
For the second case, before seat rearrangement, the state is shown as follows.
1 2
3 4
There are some possible arrangements. For example
2 4
1 3
or
2 1
4 3
is valid arrangement.
Input
Input consists of multiple datasets. Each dataset consists of 2 integers. The last input contains two 0. A dataset is given by the following format.
r c
Input satisfies the following constraint.
1 ≤ r ≤ 19, 1 ≤ c ≤ 19
Output
Print "yes" without quates in one line if it is possible to rearrange the seats, otherwise print "no" without quates in one line.
Example
Input
1 1
2 2
0 0
Output
no
yes | instruction | 0 | 106,970 | 14 | 213,940 |
"Correct Solution:
```
while True:
a,b = map(int, input().split())
if a == 0 and b == 0:
break
if a%2 == 0 or b%2 == 0:
print("yes")
else:
print("no")
``` | output | 1 | 106,970 | 14 | 213,941 |
Provide a correct Python 3 solution for this coding contest problem.
Haruna is a high school student. She must remember the seating arrangements in her class because she is a class president. It is too difficult task to remember if there are so many students.
That is the reason why seating rearrangement is depress task for her. But students have a complaint if seating is fixed.
One day, she made a rule that all students must move but they don't move so far as the result of seating rearrangement.
The following is the rule. The class room consists of r*c seats. Each r row has c seats. The coordinate of the front row and most left is (1,1). The last row and right most is (r,c). After seating rearrangement, all students must move next to their seat. If a student sit (y,x) before seating arrangement, his/her seat must be (y,x+1) , (y,x-1), (y+1,x) or (y-1,x). The new seat must be inside of the class room. For example (0,1) or (r+1,c) is not allowed.
Your task is to check whether it is possible to rearrange seats based on the above rule.
Hint
For the second case, before seat rearrangement, the state is shown as follows.
1 2
3 4
There are some possible arrangements. For example
2 4
1 3
or
2 1
4 3
is valid arrangement.
Input
Input consists of multiple datasets. Each dataset consists of 2 integers. The last input contains two 0. A dataset is given by the following format.
r c
Input satisfies the following constraint.
1 ≤ r ≤ 19, 1 ≤ c ≤ 19
Output
Print "yes" without quates in one line if it is possible to rearrange the seats, otherwise print "no" without quates in one line.
Example
Input
1 1
2 2
0 0
Output
no
yes | instruction | 0 | 106,971 | 14 | 213,942 |
"Correct Solution:
```
while True:
r, c = map(int, input().split())
if r == 0:
break
print(["yes", "no"][c % 2 and r % 2])
``` | output | 1 | 106,971 | 14 | 213,943 |
Provide a correct Python 3 solution for this coding contest problem.
Haruna is a high school student. She must remember the seating arrangements in her class because she is a class president. It is too difficult task to remember if there are so many students.
That is the reason why seating rearrangement is depress task for her. But students have a complaint if seating is fixed.
One day, she made a rule that all students must move but they don't move so far as the result of seating rearrangement.
The following is the rule. The class room consists of r*c seats. Each r row has c seats. The coordinate of the front row and most left is (1,1). The last row and right most is (r,c). After seating rearrangement, all students must move next to their seat. If a student sit (y,x) before seating arrangement, his/her seat must be (y,x+1) , (y,x-1), (y+1,x) or (y-1,x). The new seat must be inside of the class room. For example (0,1) or (r+1,c) is not allowed.
Your task is to check whether it is possible to rearrange seats based on the above rule.
Hint
For the second case, before seat rearrangement, the state is shown as follows.
1 2
3 4
There are some possible arrangements. For example
2 4
1 3
or
2 1
4 3
is valid arrangement.
Input
Input consists of multiple datasets. Each dataset consists of 2 integers. The last input contains two 0. A dataset is given by the following format.
r c
Input satisfies the following constraint.
1 ≤ r ≤ 19, 1 ≤ c ≤ 19
Output
Print "yes" without quates in one line if it is possible to rearrange the seats, otherwise print "no" without quates in one line.
Example
Input
1 1
2 2
0 0
Output
no
yes | instruction | 0 | 106,972 | 14 | 213,944 |
"Correct Solution:
```
# AOJ 1072: Rearranging Seats
# Python3 2018.7.10 bal4u
while True:
r, c = map(int, input().split())
if r == 0: break
print("no" if r*c & 1 else "yes")
``` | output | 1 | 106,972 | 14 | 213,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food.
Iahub asks Iahubina: can you build a rooted tree, such that
* each internal node (a node with at least one son) has at least two sons;
* node i has ci nodes in its subtree?
Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. The required tree must contain n nodes.
Input
The first line of the input contains integer n (1 ≤ n ≤ 24). Next line contains n positive integers: the i-th number represents ci (1 ≤ ci ≤ n).
Output
Output on the first line "YES" (without quotes) if there exist at least one tree following Iahub's restrictions, otherwise output "NO" (without quotes).
Examples
Input
4
1 1 1 4
Output
YES
Input
5
1 1 5 2 1
Output
NO | instruction | 0 | 107,329 | 14 | 214,658 |
Tags: bitmasks, constructive algorithms, dp, greedy, trees
Correct Solution:
```
def DFS(x):
for i in range(x):
if(Seen[i][x]):
continue
if(Rem[i]>=C[x]):
if(Rem[i]==C[x] and len(Children[i])==0):
continue
Rem[i]-=C[x]
Parent[x]=i
Children[i].append(x)
return True
for i in range(x):
if(Seen[i][x]):
continue
Y=[]
for j in range(len(Children[i])):
child=Children[i][j]
Parent[child]=-1
Rem[i]+=C[child]
Seen[i][child]=True
Seen[child][i]=True
if(DFS(child)):
Seen[i][child]=False
Seen[child][i]=False
continue
Seen[i][child]=False
Seen[child][i]=False
Parent[child]=i
Rem[i]-=C[child]
Y.append(child)
Children[i]=list(Y)
if(Rem[i]>=C[x]):
if(Rem[i]==C[x] and len(Children[i])==0):
continue
Rem[i]-=C[x]
Children[i].append(x)
Parent[x]=i
return True
return False
n=int(input())
C=list(map(int,input().split()))
Rem=[-1]*n
Parent=[-1]*n
Children=[]
Seen=[]
for i in range(n):
Seen.append([False]*n)
C.sort(reverse=True)
if(C[0]!=n or C.count(2)>0):
print("NO")
else:
for i in range(n):
Rem[i]=C[i]-1
Children.append([])
Parent[0]=0
Ans="YES"
for i in range(1,n):
if(DFS(i)==False):
Ans="NO"
break
for i in range(n):
if(Rem[i]!=0 and C[i]!=1):
Ans="NO"
break
print(Ans)
``` | output | 1 | 107,329 | 14 | 214,659 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food.
Iahub asks Iahubina: can you build a rooted tree, such that
* each internal node (a node with at least one son) has at least two sons;
* node i has ci nodes in its subtree?
Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. The required tree must contain n nodes.
Input
The first line of the input contains integer n (1 ≤ n ≤ 24). Next line contains n positive integers: the i-th number represents ci (1 ≤ ci ≤ n).
Output
Output on the first line "YES" (without quotes) if there exist at least one tree following Iahub's restrictions, otherwise output "NO" (without quotes).
Examples
Input
4
1 1 1 4
Output
YES
Input
5
1 1 5 2 1
Output
NO | instruction | 0 | 107,330 | 14 | 214,660 |
Tags: bitmasks, constructive algorithms, dp, greedy, trees
Correct Solution:
```
def DFS(x):
for i in range(x):
if(Seen[i][x]):
continue
if(Rem[i]>=C[x]):
if(Rem[i]==C[x] and len(Children[i])==0):
continue
Rem[i]-=C[x]
Parent[x]=i
Children[i].append(x)
return True
for i in range(x):
if(Seen[i][x]):
continue
Y=[]
for j in range(len(Children[i])):
child=Children[i][j]
if(Seen[i][child]):
continue
Parent[child]=-1
Rem[i]+=C[child]
Seen[i][child]=True
Seen[child][i]=True
if(DFS(child)):
Seen[i][child]=False
Seen[child][i]=False
continue
Seen[i][child]=False
Seen[child][i]=False
Parent[child]=i
Rem[i]-=C[child]
Y.append(child)
Children[i]=list(Y)
if(Rem[i]>=C[x]):
if(Rem[i]==C[x] and len(Children[i])==0):
continue
Rem[i]-=C[x]
Children[i].append(x)
Parent[x]=i
return True
return False
n=int(input())
C=list(map(int,input().split()))
Rem=[-1]*n
Parent=[-1]*n
Children=[]
Seen=[]
for i in range(n):
Seen.append([False]*n)
C.sort(reverse=True)
if(C[0]!=n or C.count(2)>0):
print("NO")
else:
for i in range(n):
Rem[i]=C[i]-1
Children.append([])
Parent[0]=0
Ans="YES"
for i in range(1,n):
if(DFS(i)==False):
Ans="NO"
break
for i in range(n):
if(Rem[i]!=0 and C[i]!=1):
Ans="NO"
break
print(Ans)
``` | output | 1 | 107,330 | 14 | 214,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food.
Iahub asks Iahubina: can you build a rooted tree, such that
* each internal node (a node with at least one son) has at least two sons;
* node i has ci nodes in its subtree?
Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. The required tree must contain n nodes.
Input
The first line of the input contains integer n (1 ≤ n ≤ 24). Next line contains n positive integers: the i-th number represents ci (1 ≤ ci ≤ n).
Output
Output on the first line "YES" (without quotes) if there exist at least one tree following Iahub's restrictions, otherwise output "NO" (without quotes).
Examples
Input
4
1 1 1 4
Output
YES
Input
5
1 1 5 2 1
Output
NO | instruction | 0 | 107,331 | 14 | 214,662 |
Tags: bitmasks, constructive algorithms, dp, greedy, trees
Correct Solution:
```
def DFS(x):
for i in range(x):
if(Seen[i][x]):
continue
if(Rem[i]>=C[x]):
if(Rem[i]==C[x] and len(Children[i])==0):
continue
Rem[i]-=C[x]
Parent[x]=i
Children[i].append(x)
return True
for i in range(x):
if(Seen[i][x]):
continue
Y=[]
for j in range(len(Children[i])):
child=Children[i][j]
if(Seen[i][child]):
continue
Parent[child]=-1
Rem[i]+=C[child]
Seen[i][child]=True
Seen[child][i]=True
if(DFS(child)):
Seen[i][child]=False
Seen[child][i]=False
continue
Seen[i][child]=False
Seen[child][i]=False
Parent[child]=i
Rem[i]-=C[child]
Y.append(child)
Children[i]=list(Y)
if(Rem[i]>=C[x]):
if(Rem[i]==C[x] and len(Children[i])==0):
continue
Rem[i]-=C[x]
Children[i].append(x)
Parent[x]=i
return True
return False
n=int(input())
C=list(map(int,input().split()))
Rem=[-1]*n
Parent=[-1]*n
Children=[]
Seen=[]
for i in range(n):
Seen.append([False]*n)
C.sort(reverse=True)
if(C[0]!=n or C.count(2)>0):
print("NO")
else:
for i in range(n):
Rem[i]=C[i]-1
Children.append([])
Parent[0]=0
Ans="YES"
for i in range(1,n):
if(DFS(i)==False):
Ans="NO"
break
for i in range(n):
if(Rem[i]!=0 and C[i]!=1):
Ans="NO"
break
print(Ans)
# Made By Mostafa_Khaled
``` | output | 1 | 107,331 | 14 | 214,663 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.
Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?
In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle:
* on each holiday day the Hedgehog will necessarily receive a present,
* he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day).
For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).
Input
The first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N).
The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.
Output
Print a single number — the minimal number of presents the Hedgehog will receive over the following N days.
Examples
Input
5 2
1 3
Output
3
Input
10 1
3 6 7 8
Output
10 | instruction | 0 | 107,375 | 14 | 214,750 |
Tags: implementation
Correct Solution:
```
def cpd(fd,sd,k):
d=sd-fd-1
return d//k
n,k=[int(x) for x in input().split(' ')]
vp=[int(x) for x in input().split(' ')]
np=vp[0]
vp[0]=0
vp.append(n+1)
sm=len(vp)-2
for c in range(len(vp)-1):
sm+=cpd(vp[c],vp[c+1],k)
print(sm)
``` | output | 1 | 107,375 | 14 | 214,751 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.
Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?
In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle:
* on each holiday day the Hedgehog will necessarily receive a present,
* he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day).
For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).
Input
The first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N).
The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.
Output
Print a single number — the minimal number of presents the Hedgehog will receive over the following N days.
Examples
Input
5 2
1 3
Output
3
Input
10 1
3 6 7 8
Output
10 | instruction | 0 | 107,376 | 14 | 214,752 |
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
c = list(map(int, input().split()))[1:]
present = [0] * n
for i in c:
present[i - 1] = 1
prev = -1
d = 0
for i in range(n):
if i - prev == k:
d += 1
prev = i
elif present[i] == 1:
prev = i
d += 1
print(d)
``` | output | 1 | 107,376 | 14 | 214,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.
Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?
In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle:
* on each holiday day the Hedgehog will necessarily receive a present,
* he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day).
For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).
Input
The first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N).
The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.
Output
Print a single number — the minimal number of presents the Hedgehog will receive over the following N days.
Examples
Input
5 2
1 3
Output
3
Input
10 1
3 6 7 8
Output
10 | instruction | 0 | 107,377 | 14 | 214,754 |
Tags: implementation
Correct Solution:
```
import math
# from _54AArray import *
# from colorama import Fore,Back,Style,init
# from pipenv.vendor.yaspin.termcolor import colored
def print_input():
print("n is",n)
print("k is",k)
print("c is",c)
def func_exe(n,k,c):
cn = len(c)
if cn == 0:
res = math.floor(n/k)
return res
elif cn == 1:
midVal = 1
downVal = math.floor((c[0]-1)/k)
upVal = math.floor((n-c[cn-1])/k)
res = downVal + upVal + midVal
return res
else:
midVal = 1
downVal = math.floor((c[0]-1)/k)
upVal = math.floor((n-c[cn-1])/k)
for i in range(1,cn):
if (c[i] - c[i-1]) % k == 0:
temp = math.floor((c[i] - c[i-1])/k)
midVal += (temp )
else:
temp = math.floor((c[i] - c[i-1])/k)
midVal += (temp +1)
res = downVal + upVal + midVal
return res
def checkCase():
print(colored("Check case: ",'yellow'))
for i in range(testCase):
print("Test case Number: ",i)
print(nT[i],kT[i])
print(cnT[i],cT[i])
if func_exe(nT[i],kT[i],cT[i])[0] == ansT[i]:
print(colored("My output: "+ str(func_exe(nT[i],kT[i],cT[i])),'green'))
print(colored("Jury's output: "+ str(ansT[i]),'green'))
else:
print(colored("My output: "+ str(func_exe(nT[i],kT[i],cT[i])),'red'))
print(colored("Jury's output: "+ str(ansT[i]),'red'))
# Check down mid up
#print(print(colored("Jury's output: "+ str(ansT[i]),'red')))
# If output has many lines
# func_input()
# print_input()
n,k = [int(a) for a in input().split() ]
c = [int(a) for a in input().split()]
c.pop(0)
print(func_exe(n,k,c))
``` | output | 1 | 107,377 | 14 | 214,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.
Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?
In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle:
* on each holiday day the Hedgehog will necessarily receive a present,
* he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day).
For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).
Input
The first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N).
The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.
Output
Print a single number — the minimal number of presents the Hedgehog will receive over the following N days.
Examples
Input
5 2
1 3
Output
3
Input
10 1
3 6 7 8
Output
10 | instruction | 0 | 107,378 | 14 | 214,756 |
Tags: implementation
Correct Solution:
```
def find_in_range(arr: list, start: int, end: int) -> int:
for i in range(start, end + 1):
if i in arr:
return i
return -1
n, k = [int(item) for item in input().split(" ")]
holidays = [int(item) for item in input().split(" ")]
# holidays.remove(holidays[0])
del holidays[0]
ans, start, end = 0, 1, k
while start <= n:
day = find_in_range(holidays, start, end)
if day == -1 and start + k - 1 > n:
break
if day == -1:
start = end + 1
else:
start = day + 1
end = start + k - 1 if start + k - 1 <= n else n
ans += 1
print(ans)
``` | output | 1 | 107,378 | 14 | 214,757 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.