text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R.
Constraints
* 1 ≤ K ≤ N ≤ 40
* 1 ≤ ai ≤ 1016
* 1 ≤ L ≤ R ≤ 1016
* All input values are given in integers
Input
The input is given in the following format.
N K L R
a1 a2 ... aN
Output
Print the number of combinations in a line.
Examples
Input
2 2 1 9
5 1
Output
1
Input
5 2 7 19
3 5 4 2 2
Output
5
Submitted Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
def makeItems(lst, size):
length = len(lst)
ret = [[] for _ in range(size + 2)]
ret[0] = [0]
for a in lst:
for b in range(size, -1, -1):
add = [a + c for c in ret[b]]
ret[b + 1].extend(add)
return ret
def main():
n, k, l, r = map(int, input().split())
aList = list(map(int, input().split()))
aLeft = aList[:n // 2]
aRight = aList[n // 2:]
leftItems = makeItems(aLeft, k)
rightItems = makeItems(aRight, k)
for lst in rightItems:
lst.sort()
ans = 0
for i, lst in enumerate(leftItems):
if i > k:continue
for item in lst:
minLimit = l - item
maxLimit = r - item
left = bl(rightItems[k - i], minLimit)
right = br(rightItems[k - i], maxLimit)
ans += right - left
print(ans)
main()
```
Yes
| 104,400 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R.
Constraints
* 1 ≤ K ≤ N ≤ 40
* 1 ≤ ai ≤ 1016
* 1 ≤ L ≤ R ≤ 1016
* All input values are given in integers
Input
The input is given in the following format.
N K L R
a1 a2 ... aN
Output
Print the number of combinations in a line.
Examples
Input
2 2 1 9
5 1
Output
1
Input
5 2 7 19
3 5 4 2 2
Output
5
Submitted Solution:
```
from bisect import bisect_left, bisect_right
from itertools import combinations
if __name__ == "__main__":
N, K, L, R = map(lambda x: int(x), input().split())
coins = list(map(lambda x: int(x), input().split()))
N_half = N // 2
c1 = [list(map(sum, combinations(coins[:N_half], i))) for i in range(0, N_half + 1)]
c2 = [list(map(sum, combinations(coins[N_half:], i)))
for i in range(0, N - N_half + 1)]
for i in range(0, N - N_half + 1):
c2[i].sort()
ans = 0
for i in range(0, K + 1):
if K - i < 0 or K - i > N - N_half or i > N_half:
continue
for a in c1[i]:
low = bisect_left(c2[K - i], L - a) # type: ignore
high = bisect_right(c2[K - i], R - a) # type: ignore
ans += high - low
print(ans)
```
Yes
| 104,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R.
Constraints
* 1 ≤ K ≤ N ≤ 40
* 1 ≤ ai ≤ 1016
* 1 ≤ L ≤ R ≤ 1016
* All input values are given in integers
Input
The input is given in the following format.
N K L R
a1 a2 ... aN
Output
Print the number of combinations in a line.
Examples
Input
2 2 1 9
5 1
Output
1
Input
5 2 7 19
3 5 4 2 2
Output
5
Submitted Solution:
```
import sys
import bisect
def main():
n, K, L, R = map(int, sys.stdin.readline().split())
a = tuple(map(int, sys.stdin.readline().split()))
m = n//2
ls = [[] for _ in range(m+1)]
for i in range(1 << m):
cnt = 0
val = 0
for j in range(m):
if i >> j & 1:
cnt += 1
val += a[j]
bisect.insort_left(ls[cnt], val)
ans = 0
for i in range(1 << n-m):
cnt = 0
val = 0
for j in range(n-m):
if i >> j & 1:
cnt += 1
val += a[m+j]
if K-m <= cnt <= K:
ans += bisect.bisect_right(ls[K-cnt], R-val) - bisect.bisect_right(ls[K-cnt], L-val-1)
print(ans)
if __name__ == '__main__':
main()
```
No
| 104,402 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R.
Constraints
* 1 ≤ K ≤ N ≤ 40
* 1 ≤ ai ≤ 1016
* 1 ≤ L ≤ R ≤ 1016
* All input values are given in integers
Input
The input is given in the following format.
N K L R
a1 a2 ... aN
Output
Print the number of combinations in a line.
Examples
Input
2 2 1 9
5 1
Output
1
Input
5 2 7 19
3 5 4 2 2
Output
5
Submitted Solution:
```
from itertools import combinations as C
N, K, L, R= map(int, input().split())
a = list(map(int, input().split()))
v = [i for i in range(N)]
ans = 0
for ii in list(C(v, K)):
tmp = 0
flag = True
for i in ii:
tmp += a[i]
if tmp > R:
flag = False
break
if flag and tmp >= L:
ans += 1
print(ans)
```
No
| 104,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R.
Constraints
* 1 ≤ K ≤ N ≤ 40
* 1 ≤ ai ≤ 1016
* 1 ≤ L ≤ R ≤ 1016
* All input values are given in integers
Input
The input is given in the following format.
N K L R
a1 a2 ... aN
Output
Print the number of combinations in a line.
Examples
Input
2 2 1 9
5 1
Output
1
Input
5 2 7 19
3 5 4 2 2
Output
5
Submitted Solution:
```
import sys
import bisect
def main():
n, K, L, R = map(int, sys.stdin.readline().split())
a = tuple(map(int, sys.stdin.readline().split()))
m = n//2
ls = [[] for _ in range(m+1)]
for i in range(1 << m):
cnt = 0
val = 0
for j in range(m):
if i >> j & 1:
cnt += 1
val += a[j]
bisect.insort_left(ls[cnt], val)
for i in range(m):
ls[i].sort()
ans = 0
for i in range(1 << n-m):
cnt = 0
val = 0
for j in range(n-m):
if i >> j & 1:
cnt += 1
val += a[m+j]
if K-m <= cnt <= K:
ans += bisect.bisect_right(ls[K-cnt], R-val) - bisect.bisect_right(ls[K-cnt], L-val-1)
print(ans)
if __name__ == '__main__':
main()
```
No
| 104,404 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R.
Constraints
* 1 ≤ K ≤ N ≤ 40
* 1 ≤ ai ≤ 1016
* 1 ≤ L ≤ R ≤ 1016
* All input values are given in integers
Input
The input is given in the following format.
N K L R
a1 a2 ... aN
Output
Print the number of combinations in a line.
Examples
Input
2 2 1 9
5 1
Output
1
Input
5 2 7 19
3 5 4 2 2
Output
5
Submitted Solution:
```
import sys
def bisect(ls, value):
l, r = -1, len(ls)
while r-l>1:
mid = (l+r)//2
if ls[mid] <= value:
l = mid
else:
r = mid
return r
def main():
n, K, L, R = map(int, sys.stdin.readline().split())
a = tuple(map(int, sys.stdin.readline().split()))
m = n // 2
ls = [[] for _ in range(m + 1)]
for i in range(1 << m):
cnt = 0
val = 0
for j in range(m):
if i >> j & 1:
cnt += 1
val += a[j]
ls[cnt].append(val)
for i in range(m + 1):
ls[i].sort()
ans = 0
for i in range(1 << n - m):
cnt = 0
val = 0
for j in range(n - m):
if i >> j & 1:
cnt += 1
val += a[m + j]
if K - m <= cnt <= K:
ans += bisect(ls[K - cnt], R - val) - bisect(ls[K - cnt], L - val - 1)
print(ans)
if __name__ == '__main__':
main()
```
No
| 104,405 |
Provide a correct Python 3 solution for this coding contest problem.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
"Correct Solution:
```
a, b = [int(x) for x in input().split()]
c = abs(a) // abs(b)
print(-c if a ^ b < 0 else c)
```
| 104,406 |
Provide a correct Python 3 solution for this coding contest problem.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
"Correct Solution:
```
m,n=map(int,input().split())
if m<0 and n>0:
m*=-1
print(-(m//n))
elif m>0 and n<0:
n*=-1
print(-(m//n))
else:
print(m//n)
```
| 104,407 |
Provide a correct Python 3 solution for this coding contest problem.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
"Correct Solution:
```
a, b = map(int, input().split())
c = abs(a) // abs(b)
print(-1 * c if a * b < 0 else c)
```
| 104,408 |
Provide a correct Python 3 solution for this coding contest problem.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
"Correct Solution:
```
a,b = map(int,input().split())
if(a*b<0):
print(abs(a)//abs(b)*-1)
else:
print(abs(a)//abs(b))
```
| 104,409 |
Provide a correct Python 3 solution for this coding contest problem.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
"Correct Solution:
```
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l(): #intのlist
return list(map(int,input().split()))
def m(): #複数文字
return map(int,input().split())
def onem(): #Nとかの取得
return int(input())
def s(x): #圧縮
a = []
aa = x[0]
su = 1
for i in range(len(x)-1):
if aa == x[i+1]:
a.append([aa,su])
aa = x[i+1]
su = 1
else:
su += 1
a.append([aa,su])
return a
def jo(x): #listをスペースごとに分ける
return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
return max(map(max,x))
n,m= m()
if n*m > 0:
print(n//m)
else:
print(-(-n//m))
```
| 104,410 |
Provide a correct Python 3 solution for this coding contest problem.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
"Correct Solution:
```
a,b = map(int,input().split())
if a*b > 0:
print(a//b)
else:
print(-1*(abs(a)//abs(b)))
```
| 104,411 |
Provide a correct Python 3 solution for this coding contest problem.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Big Integers - Division of Big Integers
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=NTL_2_D&lang=jp
"""
import sys
def main(args):
A, B = map(int, input().split())
sign = 1 if A*B >= 0 else -1
print(abs(A) // abs(B) * sign)
if __name__ == '__main__':
main(sys.argv[1:])
```
| 104,412 |
Provide a correct Python 3 solution for this coding contest problem.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
"Correct Solution:
```
a,b = map(int,input().split())
base = 10**1000
sign = (a<0) ^ (b<0)
print(((-1)**sign)*(abs(a)//abs(b)))
```
| 104,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
Submitted Solution:
```
a,b=map(int, input().split())
c=abs(a)//abs(b)
print(c*(-1)**(a*b<0))
```
Yes
| 104,414 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
Submitted Solution:
```
import decimal
def main():
a, b = map(int, input().split())
decimal.getcontext().prec = len(str(a))
print(int(decimal.Decimal(a)/decimal.Decimal(b)))
main()
```
Yes
| 104,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
Submitted Solution:
```
a,b = map(int,input().split())
print(a//b if a*b > 0 else -(-a//b))
```
Yes
| 104,416 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
Submitted Solution:
```
a, b = map(int, input().split());print(((a // abs(a)) if a != 0 else 1)* (b // abs(b)) * (abs(a) // abs(b)))
```
Yes
| 104,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
Submitted Solution:
```
import math
import decimal
def main():
a, b = map(int, input().split())
decimal.getcontext().prec = int(math.log10(a)) + 1
print(int(decimal.Decimal(a)/decimal.Decimal(b)))
main()
```
No
| 104,418 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
Submitted Solution:
```
from decimal import *
a,b = map(int, input().split())
print(int(Decimal(a)/Decimal(b)))
```
No
| 104,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
Submitted Solution:
```
a,b = map(int,input().split())
print(int(a / b))
```
No
| 104,420 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Division of Big Integers
Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the quotient in a line.
Constraints
* $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$
* $B \ne 0$
Sample Input 1
5 8
Sample Output 1
0
Sample Input 2
100 25
Sample Output 2
4
Sample Input 3
-1 3
Sample Output 3
0
Sample Input 4
12 -3
Sample Output 4
-4
Example
Input
5 8
Output
0
Submitted Solution:
```
def div_round(x, y): return (x + (y // 2)) // y
a, b = map(int, input().split())
print(div_round(a, b))
```
No
| 104,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Tags: constructive algorithms, graphs
Correct Solution:
```
from sys import exit
def bad():
print("NO")
exit()
node = 1
def make_branch(u, d, deg, g, n, k):
global node
while deg[u] < k and d > 0 and node < n:
node += 1
deg[u] += 1
deg[node] = 1
g[u].append(node)
make_branch(node, d - 1, deg, g, n, k)
def main():
global node
n, d, k = map(int, input().split())
if d >= n or (k == 1 and n > 2):
bad()
g = [[] for _ in range(n + 5)]
deg = [0 for _ in range(n + 5)]
for i in range(1, d + 1):
g[i].append(i + 1)
deg[i] += 1
deg[i + 1] += 1
node = d + 1
LD = 1
RD = d - 1
for u in range(2, d + 1):
make_branch(u, min(LD, RD), deg, g, n, k)
LD += 1
RD -= 1
used = [False for _ in range(n + 5)]
q = [[1, 1]]
used[1] = True
while len(q) > 0:
u, p = q.pop()
for v in g[u]:
if v != p:
used[v] = True
q.append([v, u])
for i in range(1, n + 1):
if used[i] == False:
bad()
print("YES")
for u in range(1, n + 1):
for v in g[u]:
print(u, v)
main()
```
| 104,422 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Tags: constructive algorithms, graphs
Correct Solution:
```
n, d, k = map(int, input().split())
if d+1 > n:
print('NO')
exit()
ans = []
dist = [0]*n
deg = [0]*n
for i in range(d+1):
if i == 0 or i == d:
deg[i] = 1
else:
deg[i] = 2
if i != d:
ans.append((i+1, i+2))
dist[i] = max(i, d-i)
for i in range(n):
if deg[i] > k:
print('NO')
exit()
from collections import deque
q = deque(list(range(d+1)))
cur = d+1
while q and cur < n:
v = q.popleft()
if dist[v] < d and deg[v] < k:
deg[v] += 1
dist[cur] = dist[v]+1
deg[cur] = 1
ans.append((v+1, cur+1))
q.append(v)
q.append(cur)
cur += 1
else:
continue
if cur != n:
print('NO')
else:
print('YES')
for i in range(len(ans)):
print(*ans[i])
```
| 104,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Tags: constructive algorithms, graphs
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
from collections import deque
n,d,k=map(int,input().split())
if d>=n:
print("NO")
exit()
graph=[[] for i in range(n+1)]
for i in range(1,d+2):
graph[i].append(min(i-1,d+1-i))
# print(graph)
for i in range(1,d+1):
graph[i].append(i+1)
graph[i+1].append(i)
# print(graph)
deg=[0]*(n+1)
deg[1]=1
deg[d+1]=1
for i in range(2,d+1):
deg[i]=2
# print(deg)
for i in deg:
if i>k:
print("NO")
exit()
p=d+2
for i in range(1,d+2):
q=deque()
q.append(i)
while len(q)!=0:
x=q.popleft()
while (graph[x][0]>0 and deg[x]<k and p<=n):
graph[x].append(p)
deg[x]=deg[x]+1
graph[p].append(graph[x][0]-1)
graph[p].append(x)
deg[p]=deg[p]+1
q.append(p)
p=p+1
# print(graph)
if p<=n:
print("NO")
else:
print("YES")
vis=[-1]*(n+1)
for i in range(1,d+2):
if vis[i]==-1:
q=deque()
q.append(i)
while len(q)!=0:
x=q.popleft()
vis[x]=1
for j in range(1,len(graph[x])):
if vis[graph[x][j]]==-1:
print(x,graph[x][j])
q.append(graph[x][j])
```
| 104,424 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Tags: constructive algorithms, graphs
Correct Solution:
```
#WARNING This code is just for fun. Reading it might give u a brainfreeze
n,d,k = [int(x) for x in input().strip().split(' ')]
l = []
i = 1
if n<=d:
print("NO")
elif k==1:
if n>2:
print("NO")
elif n==2:
print("YES")
print(1,2)
else:
n+=1
flag = False
while i<min(d+1,n):
l.append(str(i)+" "+str(i+1))
i+=1
i+=1
cnt1=0
cnt2=1
se=[[2,d+1,1]]
while cnt1<cnt2:
start = se[cnt1][0]
end = se[cnt1][1]
mode = se[cnt1][2]
#print(se)
kk = 3
while (i<n) and (kk<=k):
if i<n and not flag:
j = start
#print(j,"kk")
while i<n and j<end:
if mode==1:
c = min(j-start+1,end-j)
else:
c = min(end-j,d-end+j)
if c>1:
se.append([i,i+c-1,2])
cnt2+=1
ki=j
while i<n and c>0:
l.append(str(ki)+" "+str(i))
#print(j,i,c)
c-=1
ki=i
i+=1
j+=1
else:
flag = True
break
kk+=1
cnt1+=1
if i<n or flag:
#print(l)
print("NO")
else:
print("YES")
print('\n'.join(l))
```
| 104,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Tags: constructive algorithms, graphs
Correct Solution:
```
import sys
n,d,k=map(int,input().split())
if(n<=d):
print('NO')
sys.exit()
if(k==1 and n>2):
print('NO')
sys.exit()
edgestot=[]
edges=[[] for i in range(n)]
tovisit=[]
for i in range(d):
edgestot.append([i,i+1])
tovisit.append([i+1,min(i+1,d-i-1)])
edges[i].append(i+1)
edges[i+1].append(i)
cur=d+1
while(cur<n and len(tovisit)>0):
x=tovisit.pop()
if(x[1]==0):
continue
while(len(edges[x[0]])<k and cur<n):
tovisit.append([cur,x[1]-1])
edgestot.append([cur,x[0]])
edges[x[0]].append(cur)
edges[cur].append(x[0])
cur+=1
#print(edgestot)
if(len(edgestot)==n-1):
print('YES')
for i in range(n-1):
print(edgestot[i][0]+1,edgestot[i][1]+1)
else:
print('NO')
```
| 104,426 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Tags: constructive algorithms, graphs
Correct Solution:
```
def main():
n, d, k = list(map(int, input().split()))
if n == 2 and d == 1 and k == 1:
print("YES")
print("1 2")
return 0
if n == d + 1 and k - 1:
print("YES")
for i in range(1, d + 1):
print(i, i + 1)
return 0
if n < d +1 or k <= 2 or d == 1:
print("NO")
return 0
if d % 2 == 0:
if n * (k - 2) > -2 + k * (k - 1) ** (d // 2):
print("NO")
return 0
print("YES")
for i in range(1, d + 1):
print(i, i + 1)
nodes = d + 1
leaves = [1 + d // 2]
dev = 0
while True:
new_leaves = []
for i in leaves:
for j in range(k - 1 - (i <= d + 1)):
nodes += 1
print(i, nodes)
new_leaves.append(nodes)
if nodes == n:
return 0
dev += 1
leaves = new_leaves + [1 - dev + d // 2, 1 + dev + d // 2]
else:
if n * (k - 2) > -2 + k * (k - 1) ** (d // 2) + (k - 2) * (k - 1) ** (d // 2):
print("NO")
return 0
print("YES")
for i in range(1, d + 1):
print(i, i + 1)
nodes = d + 1
leaves = [1 + d // 2, 2 + d // 2]
dev = 0
while True:
new_leaves = []
for i in leaves:
for j in range(k - 1 - (i <= d + 1)):
nodes += 1
print(i, nodes)
new_leaves.append(nodes)
if nodes == n:
return 0
dev += 1
leaves = new_leaves + [1 - dev + d // 2, 2 + dev + d // 2]
main()
```
| 104,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Tags: constructive algorithms, graphs
Correct Solution:
```
n, d, k = map(int, input().split())
num = d+2
def solve():
global num
if n == 1: return 'NO'
if n == 2:
if d != 1:
return 'NO'
else:
return "YES\n1 2"
if k < 2: return 'NO'
if d > n-1: return 'NO'
depth = [min(i, d-i) for i in range(d+1)]
ans = [(i+1, i+2) for i in range(d)]
def dfs(v, depth):
global num
if depth == 0: return
for i in range(k-1):
if len(ans) == n-1: return
v2 = num
num += 1
ans.append((v, v2))
dfs(v2, depth-1)
for v in range(d+1):
if depth[v] == 0: continue
for i in range(k-2):
if len(ans) == n-1: break
v2 = num
num += 1
ans.append((v+1, v2))
if depth[v] > 1: dfs(v2, depth[v]-1)
if len(ans) < n-1: return "NO"
return "YES\n%s"%"\n".join(["%d %d"%i for i in ans])
print(solve())
```
| 104,428 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Tags: constructive algorithms, graphs
Correct Solution:
```
n,d,k=map(int,input().strip().split())
ans=[]
if (d>n-1):
print ("NO")
exit(0)
if (k<2 and n>2):
print ("NO")
exit(0)
l1=[0 for i in range(d+2)]
count=d
cnt=d+2
def insert(par,v,r,e):
global count
global cnt
if count==n-1:
print ("YES")
for o in ans:
print (o[0],o[1])
exit(0)
else:
ans.append([par,v])
cnt=cnt+1
count=count+1
if (e==0):
return
while(r!=0):
insert(v,cnt,k-1,e-1)
r=r-1
return
for i in range(1,d+1):
ans.append([i,i+1])
for i in range(1,d+2):
l1[i]=min(i-1,d+1-i)
for i in range(2,d+1):
r=k-2
while(r!=0):
insert(i,cnt,k-1,l1[i]-1)
r=r-1
if (count<n-1):
print ("NO")
else:
print ("YES")
for o in ans:
print (o[0],o[1])
exit(0)
```
| 104,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Submitted Solution:
```
"""Sorted List
==============
:doc:`Sorted Containers<index>` is an Apache2 licensed Python sorted
collections library, written in pure-Python, and fast as C-extensions. The
:doc:`introduction<introduction>` is the best way to get started.
Sorted list implementations:
.. currentmodule:: sortedcontainers
* :class:`SortedList`
* :class:`SortedKeyList`
"""
# pylint: disable=too-many-lines
from __future__ import print_function
from bisect import bisect_left, bisect_right, insort
from collections import Sequence, MutableSequence
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
###############################################################################
# BEGIN Python 2/3 Shims
###############################################################################
from functools import wraps
from sys import hexversion
if hexversion < 0x03000000:
from itertools import imap as map # pylint: disable=redefined-builtin
from itertools import izip as zip # pylint: disable=redefined-builtin
try:
from thread import get_ident
except ImportError:
from dummy_thread import get_ident
else:
from functools import reduce
try:
from _thread import get_ident
except ImportError:
from _dummy_thread import get_ident
def recursive_repr(fillvalue='...'):
"Decorator to make a repr function return fillvalue for a recursive call."
# pylint: disable=missing-docstring
# Copied from reprlib in Python 3
# https://hg.python.org/cpython/file/3.6/Lib/reprlib.py
def decorating_function(user_function):
repr_running = set()
@wraps(user_function)
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper
return decorating_function
###############################################################################
# END Python 2/3 Shims
###############################################################################
class SortedList(MutableSequence):
"""Sorted list is a sorted mutable sequence.
Sorted list values are maintained in sorted order.
Sorted list values must be comparable. The total ordering of values must
not change while they are stored in the sorted list.
Methods for adding values:
* :func:`SortedList.add`
* :func:`SortedList.update`
* :func:`SortedList.__add__`
* :func:`SortedList.__iadd__`
* :func:`SortedList.__mul__`
* :func:`SortedList.__imul__`
Methods for removing values:
* :func:`SortedList.clear`
* :func:`SortedList.discard`
* :func:`SortedList.remove`
* :func:`SortedList.pop`
* :func:`SortedList.__delitem__`
Methods for looking up values:
* :func:`SortedList.bisect_left`
* :func:`SortedList.bisect_right`
* :func:`SortedList.count`
* :func:`SortedList.index`
* :func:`SortedList.__contains__`
* :func:`SortedList.__getitem__`
Methods for iterating values:
* :func:`SortedList.irange`
* :func:`SortedList.islice`
* :func:`SortedList.__iter__`
* :func:`SortedList.__reversed__`
Methods for miscellany:
* :func:`SortedList.copy`
* :func:`SortedList.__len__`
* :func:`SortedList.__repr__`
* :func:`SortedList._check`
* :func:`SortedList._reset`
Sorted lists use lexicographical ordering semantics when compared to other
sequences.
Some methods of mutable sequences are not supported and will raise
not-implemented error.
"""
DEFAULT_LOAD_FACTOR = 1000
def __init__(self, iterable=None, key=None):
"""Initialize sorted list instance.
Optional `iterable` argument provides an initial iterable of values to
initialize the sorted list.
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList()
>>> sl
SortedList([])
>>> sl = SortedList([3, 1, 2, 5, 4])
>>> sl
SortedList([1, 2, 3, 4, 5])
:param iterable: initial values (optional)
"""
assert key is None
self._len = 0
self._load = self.DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._index = []
self._offset = 0
if iterable is not None:
self._update(iterable)
def __new__(cls, iterable=None, key=None):
"""Create new sorted list or sorted-key list instance.
Optional `key`-function argument will return an instance of subtype
:class:`SortedKeyList`.
>>> sl = SortedList()
>>> isinstance(sl, SortedList)
True
>>> sl = SortedList(key=lambda x: -x)
>>> isinstance(sl, SortedList)
True
>>> isinstance(sl, SortedKeyList)
True
:param iterable: initial values (optional)
:param key: function used to extract comparison key (optional)
:return: sorted list or sorted-key list instance
"""
# pylint: disable=unused-argument
if key is None:
return object.__new__(cls)
else:
if cls is SortedList:
return object.__new__(SortedKeyList)
else:
raise TypeError('inherit SortedKeyList for key argument')
@property
def key(self):
"""Function used to extract comparison key from values.
Sorted list compares values directly so the key function is none.
"""
return None
def _reset(self, load):
"""Reset sorted list load factor.
The `load` specifies the load-factor of the list. The default load
factor of 1000 works well for lists from tens to tens-of-millions of
values. Good practice is to use a value that is the cube root of the
list size. With billions of elements, the best load factor depends on
your usage. It's best to leave the load factor at the default until you
start benchmarking.
See :doc:`implementation` and :doc:`performance-scale` for more
information.
Runtime complexity: `O(n)`
:param int load: load-factor for sorted list sublists
"""
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._update(values)
def clear(self):
"""Remove all values from sorted list.
Runtime complexity: `O(n)`
"""
self._len = 0
del self._lists[:]
del self._maxes[:]
del self._index[:]
self._offset = 0
_clear = clear
def add(self, value):
"""Add `value` to sorted list.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList()
>>> sl.add(3)
>>> sl.add(1)
>>> sl.add(2)
>>> sl
SortedList([1, 2, 3])
:param value: value to add to sorted list
"""
_lists = self._lists
_maxes = self._maxes
if _maxes:
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
pos -= 1
_lists[pos].append(value)
_maxes[pos] = value
else:
insort(_lists[pos], value)
self._expand(pos)
else:
_lists.append([value])
_maxes.append(value)
self._len += 1
def _expand(self, pos):
"""Split sublists with length greater than double the load-factor.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
"""
_load = self._load
_lists = self._lists
_index = self._index
if len(_lists[pos]) > (_load << 1):
_maxes = self._maxes
_lists_pos = _lists[pos]
half = _lists_pos[_load:]
del _lists_pos[_load:]
_maxes[pos] = _lists_pos[-1]
_lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
del _index[:]
else:
if _index:
child = self._offset + pos
while child:
_index[child] += 1
child = (child - 1) >> 1
_index[0] += 1
def update(self, iterable):
"""Update sorted list by adding all values from `iterable`.
Runtime complexity: `O(k*log(n))` -- approximate.
>>> sl = SortedList()
>>> sl.update([3, 1, 2])
>>> sl
SortedList([1, 2, 3])
:param iterable: iterable of values to add
"""
_lists = self._lists
_maxes = self._maxes
values = sorted(iterable)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort()
self._clear()
else:
_add = self.add
for val in values:
_add(val)
return
_load = self._load
_lists.extend(values[pos:(pos + _load)]
for pos in range(0, len(values), _load))
_maxes.extend(sublist[-1] for sublist in _lists)
self._len = len(values)
del self._index[:]
_update = update
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list.
``sl.__contains__(value)`` <==> ``value in sl``
Runtime complexity: `O(log(n))`
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> 3 in sl
True
:param value: search for value in sorted list
:return: true if `value` in sorted list
"""
_maxes = self._maxes
if not _maxes:
return False
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return False
_lists = self._lists
idx = bisect_left(_lists[pos], value)
return _lists[pos][idx] == value
def discard(self, value):
"""Remove `value` from sorted list if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> sl.discard(5)
>>> sl.discard(0)
>>> sl == [1, 2, 3, 4]
True
:param value: `value` to discard from sorted list
"""
_maxes = self._maxes
if not _maxes:
return
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member.
If `value` is not a member, raise ValueError.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 3, 4, 5])
>>> sl.remove(5)
>>> sl == [1, 2, 3, 4]
True
>>> sl.remove(0)
Traceback (most recent call last):
...
ValueError: 0 not in list
:param value: `value` to remove from sorted list
:raises ValueError: if `value` is not in sorted list
"""
_maxes = self._maxes
if not _maxes:
raise ValueError('{0!r} not in list'.format(value))
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
raise ValueError('{0!r} not in list'.format(value))
_lists = self._lists
idx = bisect_left(_lists[pos], value)
if _lists[pos][idx] == value:
self._delete(pos, idx)
else:
raise ValueError('{0!r} not in list'.format(value))
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`.
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
:param int pos: lists index
:param int idx: sublist index
"""
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = (child - 1) >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
def _loc(self, pos, idx):
"""Convert an index pair (lists index, sublist index) into a single
index number that corresponds to the position of the value in the
sorted list.
Many queries require the index be built. Details of the index are
described in ``SortedList._build_index``.
Indexing requires traversing the tree from a leaf node to the root. The
parent of each node is easily computable at ``(pos - 1) // 2``.
Left-child nodes are always at odd indices and right-child nodes are
always at even indices.
When traversing up from a right-child node, increment the total by the
left-child node.
The final index is the sum from traversal and the index in the sublist.
For example, using the index from ``SortedList._build_index``::
_index = 14 5 9 3 2 4 5
_offset = 3
Tree::
14
5 9
3 2 4 5
Converting an index pair (2, 3) into a single index involves iterating
like so:
1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify
the node as a left-child node. At such nodes, we simply traverse to
the parent.
2. At node 9, position 2, we recognize the node as a right-child node
and accumulate the left-child in our total. Total is now 5 and we
traverse to the parent at position 0.
3. Iteration ends at the root.
The index is then the sum of the total and sublist index: 5 + 3 = 8.
:param int pos: lists index
:param int idx: sublist index
:return: index in sorted list
"""
if not pos:
return idx
_index = self._index
if not _index:
self._build_index()
total = 0
# Increment pos to point in the index to len(self._lists[pos]).
pos += self._offset
# Iterate until reaching the root of the index tree at pos = 0.
while pos:
# Right-child nodes are at odd indices. At such indices
# account the total below the left child node.
if not pos & 1:
total += _index[pos - 1]
# Advance pos to the parent node.
pos = (pos - 1) >> 1
return total + idx
def _pos(self, idx):
"""Convert an index into an index pair (lists index, sublist index)
that can be used to access the corresponding lists position.
Many queries require the index be built. Details of the index are
described in ``SortedList._build_index``.
Indexing requires traversing the tree to a leaf node. Each node has two
children which are easily computable. Given an index, pos, the
left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 +
2``.
When the index is less than the left-child, traversal moves to the
left sub-tree. Otherwise, the index is decremented by the left-child
and traversal moves to the right sub-tree.
At a child node, the indexing pair is computed from the relative
position of the child node as compared with the offset and the remaining
index.
For example, using the index from ``SortedList._build_index``::
_index = 14 5 9 3 2 4 5
_offset = 3
Tree::
14
5 9
3 2 4 5
Indexing position 8 involves iterating like so:
1. Starting at the root, position 0, 8 is compared with the left-child
node (5) which it is greater than. When greater the index is
decremented and the position is updated to the right child node.
2. At node 9 with index 3, we again compare the index to the left-child
node with value 4. Because the index is the less than the left-child
node, we simply traverse to the left.
3. At node 4 with index 3, we recognize that we are at a leaf node and
stop iterating.
4. To compute the sublist index, we subtract the offset from the index
of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we
simply use the index remaining from iteration. In this case, 3.
The final index pair from our example is (2, 3) which corresponds to
index 8 in the sorted list.
:param int idx: index in sorted list
:return: (lists index, sublist index) pair
"""
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError('list index out of range')
elif idx >= self._len:
raise IndexError('list index out of range')
if idx < len(self._lists[0]):
return 0, idx
_index = self._index
if not _index:
self._build_index()
pos = 0
child = 1
len_index = len(_index)
while child < len_index:
index_child = _index[child]
if idx < index_child:
pos = child
else:
idx -= index_child
pos = child + 1
child = (pos << 1) + 1
return (pos - self._offset, idx)
def _build_index(self):
"""Build a positional index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a lists representation storing integers::
0: [1, 2, 3]
1: [4, 5]
2: [6, 7, 8, 9]
3: [10, 11, 12, 13, 14]
The first transformation maps the sub-lists by their length. The
first row of the index is the length of the sub-lists::
0: [3, 2, 4, 5]
Each row after that is the sum of consecutive pairs of the previous
row::
1: [5, 9]
2: [14]
Finally, the index is built by concatenating these lists together::
_index = [14, 5, 9, 3, 2, 4, 5]
An offset storing the start of the first row is also stored::
_offset = 3
When built, the index can be used for efficient indexing into the list.
See the comment and notes on ``SortedList._pos`` for details.
"""
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1
def __delitem__(self, index):
"""Remove value at `index` from sorted list.
``sl.__delitem__(index)`` <==> ``del sl[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> del sl[2]
>>> sl
SortedList(['a', 'b', 'd', 'e'])
>>> del sl[:2]
>>> sl
SortedList(['d', 'e'])
:param index: integer or slice for indexing
:raises IndexError: if index out of range
"""
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return self._clear()
elif self._len <= 8 * (stop - start):
values = self._getitem(slice(None, start))
if stop < self._len:
values += self._getitem(slice(stop, None))
self._clear()
return self._update(values)
indices = range(start, stop, step)
# Delete items from greatest index to least so
# that the indices remain valid throughout iteration.
if step > 0:
indices = reversed(indices)
_pos, _delete = self._pos, self._delete
for index in indices:
pos, idx = _pos(index)
_delete(pos, idx)
else:
pos, idx = self._pos(index)
self._delete(pos, idx)
def __getitem__(self, index):
"""Lookup value at `index` in sorted list.
``sl.__getitem__(index)`` <==> ``sl[index]``
Supports slicing.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl[1]
'b'
>>> sl[-1]
'e'
>>> sl[2:5]
['c', 'd', 'e']
:param index: integer or slice for indexing
:return: value or list of values
:raises IndexError: if index out of range
"""
_lists = self._lists
if isinstance(index, slice):
start, stop, step = index.indices(self._len)
if step == 1 and start < stop:
if start == 0 and stop == self._len:
return reduce(iadd, self._lists, [])
start_pos, start_idx = self._pos(start)
if stop == self._len:
stop_pos = len(_lists) - 1
stop_idx = len(_lists[stop_pos])
else:
stop_pos, stop_idx = self._pos(stop)
if start_pos == stop_pos:
return _lists[start_pos][start_idx:stop_idx]
prefix = _lists[start_pos][start_idx:]
middle = _lists[(start_pos + 1):stop_pos]
result = reduce(iadd, middle, prefix)
result += _lists[stop_pos][:stop_idx]
return result
if step == -1 and start > stop:
result = self._getitem(slice(stop + 1, start + 1))
result.reverse()
return result
# Return a list because a negative step could
# reverse the order of the items and this could
# be the desired behavior.
indices = range(start, stop, step)
return list(self._getitem(index) for index in indices)
else:
if self._len:
if index == 0:
return _lists[0][0]
elif index == -1:
return _lists[-1][-1]
else:
raise IndexError('list index out of range')
if 0 <= index < len(_lists[0]):
return _lists[0][index]
len_last = len(_lists[-1])
if -len_last < index < 0:
return _lists[-1][len_last + index]
pos, idx = self._pos(index)
return _lists[pos][idx]
_getitem = __getitem__
def __setitem__(self, index, value):
"""Raise not-implemented error.
``sl.__setitem__(index, value)`` <==> ``sl[index] = value``
:raises NotImplementedError: use ``del sl[index]`` and
``sl.add(value)`` instead
"""
message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
raise NotImplementedError(message)
def __iter__(self):
"""Return an iterator over the sorted list.
``sl.__iter__()`` <==> ``iter(sl)``
Iterating the sorted list while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return chain.from_iterable(self._lists)
def __reversed__(self):
"""Return a reverse iterator over the sorted list.
``sl.__reversed__()`` <==> ``reversed(sl)``
Iterating the sorted list while adding or deleting values may raise a
:exc:`RuntimeError` or fail to iterate over all values.
"""
return chain.from_iterable(map(reversed, reversed(self._lists)))
def reverse(self):
"""Raise not-implemented error.
Sorted list maintains values in ascending sort order. Values may not be
reversed in-place.
Use ``reversed(sl)`` for an iterator over values in descending sort
order.
Implemented to override `MutableSequence.reverse` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``reversed(sl)`` instead
"""
raise NotImplementedError('use ``reversed(sl)`` instead')
def islice(self, start=None, stop=None, reverse=False):
"""Return an iterator that slices sorted list from `start` to `stop`.
The `start` and `stop` index are treated inclusive and exclusive,
respectively.
Both `start` and `stop` default to `None` which is automatically
inclusive of the beginning and end of the sorted list.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> sl = SortedList('abcdefghij')
>>> it = sl.islice(2, 6)
>>> list(it)
['c', 'd', 'e', 'f']
:param int start: start index (inclusive)
:param int stop: stop index (exclusive)
:param bool reverse: yield values in reverse order
:return: iterator
"""
_len = self._len
if not _len:
return iter(())
start, stop, _ = slice(start, stop).indices(self._len)
if start >= stop:
return iter(())
_pos = self._pos
min_pos, min_idx = _pos(start)
if stop == _len:
max_pos = len(self._lists) - 1
max_idx = len(self._lists[-1])
else:
max_pos, max_idx = _pos(stop)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
"""Return an iterator that slices sorted list using two index pairs.
The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the
first inclusive and the latter exclusive. See `_pos` for details on how
an index is converted to an index pair.
When `reverse` is `True`, values are yielded from the iterator in
reverse order.
"""
_lists = self._lists
if min_pos > max_pos:
return iter(())
if min_pos == max_pos:
if reverse:
indices = reversed(range(min_idx, max_idx))
return map(_lists[min_pos].__getitem__, indices)
indices = range(min_idx, max_idx)
return map(_lists[min_pos].__getitem__, indices)
next_pos = min_pos + 1
if next_pos == max_pos:
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
map(_lists[max_pos].__getitem__, max_indices),
)
if reverse:
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, reversed(sublist_indices))
max_indices = range(max_idx)
return chain(
map(_lists[max_pos].__getitem__, reversed(max_indices)),
chain.from_iterable(map(reversed, sublists)),
map(_lists[min_pos].__getitem__, reversed(min_indices)),
)
min_indices = range(min_idx, len(_lists[min_pos]))
sublist_indices = range(next_pos, max_pos)
sublists = map(_lists.__getitem__, sublist_indices)
max_indices = range(max_idx)
return chain(
map(_lists[min_pos].__getitem__, min_indices),
chain.from_iterable(sublists),
map(_lists[max_pos].__getitem__, max_indices),
)
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
"""Create an iterator of values between `minimum` and `maximum`.
Both `minimum` and `maximum` default to `None` which is automatically
inclusive of the beginning and end of the sorted list.
The argument `inclusive` is a pair of booleans that indicates whether
the minimum and maximum ought to be included in the range,
respectively. The default is ``(True, True)`` such that the range is
inclusive of both minimum and maximum.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
>>> sl = SortedList('abcdefghij')
>>> it = sl.irange('c', 'f')
>>> list(it)
['c', 'd', 'e', 'f']
:param minimum: minimum value to start iterating
:param maximum: maximum value to stop iterating
:param inclusive: pair of booleans
:param bool reverse: yield values in reverse order
:return: iterator
"""
_maxes = self._maxes
if not _maxes:
return iter(())
_lists = self._lists
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if minimum is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_lists[min_pos], minimum)
else:
min_pos = bisect_right(_maxes, minimum)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_lists[min_pos], minimum)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if maximum is None:
max_pos = len(_maxes) - 1
max_idx = len(_lists[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_right(_lists[max_pos], maximum)
else:
max_pos = bisect_left(_maxes, maximum)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_lists[max_pos])
else:
max_idx = bisect_left(_lists[max_pos], maximum)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
def __len__(self):
"""Return the size of the sorted list.
``sl.__len__()`` <==> ``len(sl)``
:return: size of sorted list
"""
return self._len
def bisect_left(self, value):
"""Return an index to insert `value` in the sorted list.
If the `value` is already present, the insertion point will be before
(to the left of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([10, 11, 12, 13, 14])
>>> sl.bisect_left(12)
2
:param value: insertion index of value in sorted list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_left(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_left(self._lists[pos], value)
return self._loc(pos, idx)
def bisect_right(self, value):
"""Return an index to insert `value` in the sorted list.
Similar to `bisect_left`, but if `value` is already present, the
insertion point with be after (to the right of) any existing values.
Similar to the `bisect` module in the standard library.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([10, 11, 12, 13, 14])
>>> sl.bisect_right(12)
3
:param value: insertion index of value in sorted list
:return: index
"""
_maxes = self._maxes
if not _maxes:
return 0
pos = bisect_right(_maxes, value)
if pos == len(_maxes):
return self._len
idx = bisect_right(self._lists[pos], value)
return self._loc(pos, idx)
bisect = bisect_right
_bisect_right = bisect_right
def count(self, value):
"""Return number of occurrences of `value` in the sorted list.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
>>> sl.count(3)
3
:param value: value to count in sorted list
:return: count
"""
_maxes = self._maxes
if not _maxes:
return 0
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
return 0
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
pos_right = bisect_right(_maxes, value)
if pos_right == len(_maxes):
return self._len - self._loc(pos_left, idx_left)
idx_right = bisect_right(_lists[pos_right], value)
if pos_left == pos_right:
return idx_right - idx_left
right = self._loc(pos_right, idx_right)
left = self._loc(pos_left, idx_left)
return right - left
def copy(self):
"""Return a shallow copy of the sorted list.
Runtime complexity: `O(n)`
:return: new sorted list
"""
return self.__class__(self)
__copy__ = copy
def append(self, value):
"""Raise not-implemented error.
Implemented to override `MutableSequence.append` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``sl.add(value)`` instead
"""
raise NotImplementedError('use ``sl.add(value)`` instead')
def extend(self, values):
"""Raise not-implemented error.
Implemented to override `MutableSequence.extend` which provides an
erroneous default implementation.
:raises NotImplementedError: use ``sl.update(values)`` instead
"""
raise NotImplementedError('use ``sl.update(values)`` instead')
def insert(self, index, value):
"""Raise not-implemented error.
:raises NotImplementedError: use ``sl.add(value)`` instead
"""
raise NotImplementedError('use ``sl.add(value)`` instead')
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list.
Raise :exc:`IndexError` if the sorted list is empty or index is out of
range.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl.pop()
'e'
>>> sl.pop(2)
'c'
>>> sl
SortedList(['a', 'b', 'd'])
:param int index: index of value (default -1)
:return: value
:raises IndexError: if index is out of range
"""
if not self._len:
raise IndexError('pop index out of range')
_lists = self._lists
if index == 0:
val = _lists[0][0]
self._delete(0, 0)
return val
if index == -1:
pos = len(_lists) - 1
loc = len(_lists[pos]) - 1
val = _lists[pos][loc]
self._delete(pos, loc)
return val
if 0 <= index < len(_lists[0]):
val = _lists[0][index]
self._delete(0, index)
return val
len_last = len(_lists[-1])
if -len_last < index < 0:
pos = len(_lists) - 1
loc = len_last + index
val = _lists[pos][loc]
self._delete(pos, loc)
return val
pos, idx = self._pos(index)
val = _lists[pos][idx]
self._delete(pos, idx)
return val
def index(self, value, start=None, stop=None):
"""Return first index of value in sorted list.
Raise ValueError if `value` is not present.
Index must be between `start` and `stop` for the `value` to be
considered present. The default value, None, for `start` and `stop`
indicate the beginning and end of the sorted list.
Negative indices are supported.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList('abcde')
>>> sl.index('d')
3
>>> sl.index('z')
Traceback (most recent call last):
...
ValueError: 'z' is not in list
:param value: value in sorted list
:param int start: start index (default None, start of sorted list)
:param int stop: stop index (default None, end of sorted list)
:return: index of value
:raises ValueError: if value is not present
"""
_len = self._len
if not _len:
raise ValueError('{0!r} is not in list'.format(value))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
stop = _len
if stop < 0:
stop += _len
if stop > _len:
stop = _len
if stop <= start:
raise ValueError('{0!r} is not in list'.format(value))
_maxes = self._maxes
pos_left = bisect_left(_maxes, value)
if pos_left == len(_maxes):
raise ValueError('{0!r} is not in list'.format(value))
_lists = self._lists
idx_left = bisect_left(_lists[pos_left], value)
if _lists[pos_left][idx_left] != value:
raise ValueError('{0!r} is not in list'.format(value))
stop -= 1
left = self._loc(pos_left, idx_left)
if start <= left:
if left <= stop:
return left
else:
right = self._bisect_right(value) - 1
if start <= right:
return start
raise ValueError('{0!r} is not in list'.format(value))
def __add__(self, other):
"""Return new sorted list containing all values in both sequences.
``sl.__add__(other)`` <==> ``sl + other``
Values in `other` do not need to be in sorted order.
Runtime complexity: `O(n*log(n))`
>>> sl1 = SortedList('bat')
>>> sl2 = SortedList('cat')
>>> sl1 + sl2
SortedList(['a', 'a', 'b', 'c', 't', 't'])
:param other: other iterable
:return: new sorted list
"""
values = reduce(iadd, self._lists, [])
values.extend(other)
return self.__class__(values)
__radd__ = __add__
def __iadd__(self, other):
"""Update sorted list with values from `other`.
``sl.__iadd__(other)`` <==> ``sl += other``
Values in `other` do not need to be in sorted order.
Runtime complexity: `O(k*log(n))` -- approximate.
>>> sl = SortedList('bat')
>>> sl += 'cat'
>>> sl
SortedList(['a', 'a', 'b', 'c', 't', 't'])
:param other: other iterable
:return: existing sorted list
"""
self._update(other)
return self
def __mul__(self, num):
"""Return new sorted list with `num` shallow copies of values.
``sl.__mul__(num)`` <==> ``sl * num``
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList('abc')
>>> sl * 3
SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])
:param int num: count of shallow copies
:return: new sorted list
"""
values = reduce(iadd, self._lists, []) * num
return self.__class__(values)
__rmul__ = __mul__
def __imul__(self, num):
"""Update the sorted list with `num` shallow copies of values.
``sl.__imul__(num)`` <==> ``sl *= num``
Runtime complexity: `O(n*log(n))`
>>> sl = SortedList('abc')
>>> sl *= 3
>>> sl
SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])
:param int num: count of shallow copies
:return: existing sorted list
"""
values = reduce(iadd, self._lists, []) * num
self._clear()
self._update(values)
return self
def __make_cmp(seq_op, symbol, doc):
"Make comparator method."
def comparer(self, other):
"Compare method for sorted list and sequence."
if not isinstance(other, Sequence):
return NotImplemented
self_len = self._len
len_other = len(other)
if self_len != len_other:
if seq_op is eq:
return False
if seq_op is ne:
return True
for alpha, beta in zip(self, other):
if alpha != beta:
return seq_op(alpha, beta)
return seq_op(self_len, len_other)
seq_op_name = seq_op.__name__
comparer.__name__ = '__{0}__'.format(seq_op_name)
doc_str = """Return true if and only if sorted list is {0} `other`.
``sl.__{1}__(other)`` <==> ``sl {2} other``
Comparisons use lexicographical order as with sequences.
Runtime complexity: `O(n)`
:param other: `other` sequence
:return: true if sorted list is {0} `other`
"""
comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
return comparer
__eq__ = __make_cmp(eq, '==', 'equal to')
__ne__ = __make_cmp(ne, '!=', 'not equal to')
__lt__ = __make_cmp(lt, '<', 'less than')
__gt__ = __make_cmp(gt, '>', 'greater than')
__le__ = __make_cmp(le, '<=', 'less than or equal to')
__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
__make_cmp = staticmethod(__make_cmp)
@recursive_repr()
def __repr__(self):
"""Return string representation of sorted list.
``sl.__repr__()`` <==> ``repr(sl)``
:return: string representation
"""
return '{0}({1!r})'.format(type(self).__name__, list(self))
def _check(self):
"""Check invariants of sorted list.
Runtime complexity: `O(n)`
"""
try:
assert self._load >= 4
assert len(self._maxes) == len(self._lists)
assert self._len == sum(len(sublist) for sublist in self._lists)
# Check all sublists are sorted.
for sublist in self._lists:
for pos in range(1, len(sublist)):
assert sublist[pos - 1] <= sublist[pos]
# Check beginning/end of sublists are sorted.
for pos in range(1, len(self._lists)):
assert self._lists[pos - 1][-1] <= self._lists[pos][0]
# Check _maxes index is the last value of each sublist.
for pos in range(len(self._maxes)):
assert self._maxes[pos] == self._lists[pos][-1]
# Check sublist lengths are less than double load-factor.
double = self._load << 1
assert all(len(sublist) <= double for sublist in self._lists)
# Check sublist lengths are greater than half load-factor for all
# but the last sublist.
half = self._load >> 1
for pos in range(0, len(self._lists) - 1):
assert len(self._lists[pos]) >= half
if self._index:
assert self._len == self._index[0]
assert len(self._index) == self._offset + len(self._lists)
# Check index leaf nodes equal length of sublists.
for pos in range(len(self._lists)):
leaf = self._index[self._offset + pos]
assert leaf == len(self._lists[pos])
# Check index branch nodes are the sum of their children.
for pos in range(self._offset):
child = (pos << 1) + 1
if child >= len(self._index):
assert self._index[pos] == 0
elif child + 1 == len(self._index):
assert self._index[pos] == self._index[child]
else:
child_sum = self._index[child] + self._index[child + 1]
assert child_sum == self._index[pos]
except:
import sys
import traceback
traceback.print_exc(file=sys.stdout)
print('len', self._len)
print('load', self._load)
print('offset', self._offset)
print('len_index', len(self._index))
print('index', self._index)
print('len_maxes', len(self._maxes))
print('maxes', self._maxes)
print('len_lists', len(self._lists))
print('lists', self._lists)
raise
def identity(value):
"Identity function."
return value
n, d, k = map(int, input().split())
if d >= n:
print('NO')
else:
deg = [0] * n
ans = []
free = SortedList()
for i in range(d):
deg[i] += 1
deg[i + 1] += 1
if deg[i] > k or deg[i + 1] > k:
print("NO")
exit()
ans.append((i, i + 1))
for i in range(1, d):
free.add((max(i, d - i), i))
for i in range(d + 1, n):
while len(free) > 0 and deg[free[0][1]] == k:
free.pop(0)
if len(free) == 0 or free[0][0] == d:
print('NO')
exit()
deg[i] += 1
deg[free[0][1]] += 1
ans.append((i, free[0][1]))
free.add((free[0][0] + 1, i))
print('YES')
for elem in ans:
print(elem[0] + 1, elem[1] + 1)
```
Yes
| 104,430 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Submitted Solution:
```
def construct_tree(n,d, k):
nodes = []
edges = []
if d > n - 1:
return None
if k == 1 and n > 2:
return None
for i in range(1, d+2):
current_deg = k - 1 if i == 1 or i == d + 1 else k - 2
current_depth = min(i-1, d-i+1)
if current_depth and current_deg:
nodes.append([i, min(i-1, d-i+1), current_deg])
if i < d + 1:
edges.append([i, i+1])
current_nodes_count = d + 2
pos = 0
while current_nodes_count < n + 1:
if pos >= len(nodes):
return None
current = nodes[pos]
if not current[2]:
pos += 1
if pos == len(nodes):
break
continue
if current[1] - 1 and k - 1:
nodes.append([current_nodes_count, current[1] - 1, k - 1])
edges.append([current[0], current_nodes_count])
current[2] -= 1
current_nodes_count += 1
if current_nodes_count == n + 1:
return edges
return None
n, d, k = [int(val) for val in input().split()]
edges = construct_tree(n, d, k)
if edges:
print('YES')
print('\n'.join(['{0} {1}'.format(e[0], e[1]) for e in edges]))
else:
print('NO')
```
Yes
| 104,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Submitted Solution:
```
def main():
n, d, k = map(int, input().split())
_min = d+1
if n < _min:
print('NO')
else:
res = []
deg = [0] * (n+1)
dist = [0] * (n+1)
stack = []
deg[1] = 1
for i in range(1, d+1):
res.append((i, i+1))
if i > 1:
deg[i] += 2
dist[i] = max(i-1, d+1-i)
dist[d+1] = d
deg[d+1] = 1
for i in range(2, d+1):
stack.append(i)
next = d+2
while stack:
if next > n:
break
v = stack.pop()
if dist[v] < d:
while next <= n and deg[v] < k:
res.append((v, next))
deg[v] += 1
deg[next] += 1
dist[next] = dist[v] + 1
if dist[next] < d:
stack.append(next)
next += 1
ok = next > n
ok &= all(deg[i] <= k for i in range(1, n+1))
ok &= all(dist[i] <= d for i in range(1, n+1))
if not ok:
print('NO')
else:
print('YES')
for e in res:
print(*e)
if __name__ == '__main__':
main()
```
Yes
| 104,432 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Submitted Solution:
```
def main():
n, d, k = map(int, input().split())
if n < d+1 or d > 1 and k == 1:
print('NO')
return
edges = [(1, 2)]
stack = []
d2 = d/2
d21 = d2+1
for node in range(2, d+1):
edges.append((node, node+1))
stack.append([node, d2-abs(d21 - node), k-2])
next_i = d+2
while next_i <= n:
if not stack:
print('NO')
return
node = stack[-1]
i, remaining_depth, remaining_degree = node
if remaining_depth == 0 or remaining_degree == 0:
stack.pop()
continue
node[2] -= 1
edges.append((i, next_i))
stack.append([next_i, remaining_depth-1, k-1])
next_i += 1
print('YES')
print('\n'.join('{} {}'.format(a, b) for a, b in edges))
main()
```
Yes
| 104,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Submitted Solution:
```
n, d, k = map(int, input().split())
if n==8 and d==5 and k==3:
print('YES')
print('2 5')
print('7 2')
print('3 7')
print('3 1')
print('1 6')
print('8 7')
print('4 3')
exit()
elif (n,d,k) == (5,4,3):
print('YES')
print('5 2')
print('4 2')
print('3 4')
print('1 3')
exit()
output = []
queue = []
n -= 1
for i in range(min(k, n)):
output.append('{0} {1}'.format(1, i+2))
queue.append((i+2, 1))
nxt = min(k, n)+2
n -= min(k, n)
prevdpt = 0
more = False
dpt = 0
while n > 0:
x, dpt = queue.pop(0)
if prevdpt == dpt:
more = True
prevdpt = dpt
for i in range(min(k-1, n)):
output.append('{0} {1}'.format(x, nxt))
queue.append((nxt, dpt+1))
nxt += 1
n -= 1
dpt += 1
dpt *= 2
if not more:
dpt -= 1
if dpt <= d:
print('YES')
for o in output:
print(o)
else:
print('NO')
```
No
| 104,434 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Submitted Solution:
```
def construct_tree(n,d, k):
nodes = []
edges = []
if d > n - 1:
return None
if k == 1 and n > 2:
return None
for i in range(1, d+2):
current_deg = k - 1 if i == 1 or i == d + 1 else k - 2
current_depth = min(i-1, d-i+1)
if current_depth and current_deg:
nodes.append([i, min(i-1, d-i+1), current_deg])
if i < d + 1:
edges.append([i, i+1])
current_nodes_count = d + 2
pos = 0
while current_nodes_count < n:
current = nodes[pos]
if not current[2]:
pos += 1
if pos == len(nodes):
break
continue
if current[1] - 1 and k - 1:
nodes.append([current_nodes_count, current[1] - 1, k - 1])
edges.append([current[0], current_nodes_count])
current[2] -= 1
current_nodes_count += 1
if current_nodes_count == n:
return edges
return None
n, d, k = [int(val) for val in input().split()]
edges = construct_tree(n, d, k)
if edges:
print('YES')
print('\n'.join(['{0} {1}'.format(e[0], e[1]) for e in edges]))
else:
print('NO')
```
No
| 104,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Submitted Solution:
```
def main():
n, d, k = map(int, input().split())
_min = d+1
if n < _min:
print('NO')
else:
res = []
deg = [0] * (n+1)
dist = [0] * (n+1)
stack = []
deg[1] = 1
for i in range(1, d+1):
res.append((i, i+1))
if i > 1:
deg[i] += 2
dist[i] = max(i-1, d+1-i)
dist[d+1] = d
deg[d+1] = 1
for i in range(2, d+1):
stack.append(i)
next = d+2
while stack:
if next > n:
break
v = stack.pop()
if dist[v] < d:
while next <= n and deg[v] < k:
res.append((v, next))
deg[v] += 1
deg[next] += 1
dist[next] = dist[v] + 1
if dist[next] < d:
stack.append(next)
next += 1
if next <= n:
print('NO')
else:
print('YES')
for e in res:
print(*e)
if __name__ == '__main__':
main()
```
No
| 104,436 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three integers n, d and k.
Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.
An undirected tree is a connected undirected graph with n - 1 edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).
Input
The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5).
Output
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Examples
Input
6 3 3
Output
YES
3 1
4 1
1 2
5 2
2 6
Input
6 2 3
Output
NO
Input
10 4 3
Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7
Input
8 5 3
Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3
Submitted Solution:
```
def main():
n, d, k = map(int, input().split())
if n < d+1:
print('NO')
return
edges = [(1, 2)]
stack = []
d2 = d/2
d21 = d2+1
for node in range(2, d+1):
edges.append((node, node+1))
stack.append([node, d2-abs(d21 - node), k-2])
next_i = d+2
while next_i <= n:
if not stack:
print('NO')
return
node = stack[-1]
i, remaining_depth, remaining_degree = node
if remaining_depth == 0 or remaining_degree == 0:
stack.pop()
continue
node[2] -= 1
edges.append((i, next_i))
stack.append([next_i, remaining_depth-1, k-1])
next_i += 1
print('YES')
print('\n'.join('{} {}'.format(a, b) for a, b in edges))
main()
```
No
| 104,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Tags: greedy
Correct Solution:
```
n,k = map(int, input().split())
s = list(map(int,input().split()))
old = 0
current = 0
idx = 0
ans = 0
while idx < len(s):
if(old != 0 and s[idx] // k == 0):
ans+= 1
old = max(s[idx] - (k-old),0)
idx+=1
continue
ans += (s[idx]+old) // k
old = (s[idx]+old) % k
idx+=1
if(old>0):
ans+=1
print(ans)
```
| 104,438 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Tags: greedy
Correct Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
res = 0
sum = 0
can = True
for i in range(n):
if sum > 0:
sum = sum + a[i]
if sum < m:
res = res + 1
sum = 0
else:
res = res + sum // m
sum = sum % m
else:
sum = sum + a[i]
res = res + sum // m
sum = sum % m
if sum > 0:
res = res + 1
print(res)
```
| 104,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Tags: greedy
Correct Solution:
```
# NTFS: pajenegod
n,k = map(int,input().split())
lis = list(map(int,input().split()))
ans = 0
for i in range(n): # Iterate over all days
ans += lis[i]//k # calculate bags required
rem = lis[i]%k # if still some bags remain
lis[i] = rem
if rem:
ans += 1 # then we need a extra bag for this
if i>=n-1:
break
lis[i+1] = max(0,lis[i+1]-(k-rem)) # since we are taking extra bag we can put some extra amount from next bag
print(ans)
```
| 104,440 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Tags: greedy
Correct Solution:
```
n, k = map(int,input().split())
nums = list(map(int,input().split()))
result = 0
remain = 0
for num in nums:
if not (num+remain)//k and remain:
result += 1
remain = 0
continue
result += (num+remain)//k
remain = (num+remain)%k
if remain:
result+=1
print(result)
```
| 104,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Tags: greedy
Correct Solution:
```
n,k=[int(x) for x in input().split()]
a=[int(x) for x in input().split()]
ans=0
pre=0
for i in range(n):
if pre!=0:
ans+=1
a[i]-=(k-pre)
if a[i]<0:a[i]=0
ans+=a[i]//k
pre=a[i]-a[i]//k*k
if pre!=0 : ans+=1
print(ans)
```
| 104,442 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Tags: greedy
Correct Solution:
```
from math import floor
n,k=map(int,input().split())
a=list(map(int,input().split()))
ans=0
i=0
rem=0
while i<n:
if i<n-1:
if a[i]+rem<=k and rem!=0:
ans+=1
i+=1
rem=0
else:
ans+=floor((a[i]+rem)/k)
rem=(a[i]+rem)%k
i+=1
elif i==n-1:
ans+=floor((a[i]+rem)/k)
rem=(a[i]+rem)%k
i+=1
if rem!=0:
ans+=1
print(ans)
```
| 104,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Tags: greedy
Correct Solution:
```
n,k = map(int,input().split())
t = list(map(int,input().split()))
t_bool = []
for x in range(0,len(t),+1):
t_bool.append(False)
wyn = 0
r = 0
przel = False
for x in range(0,len(t),+1):
if t_bool[x]==True:
if t[x]!=0:
wyn+=1
t[x] -= k
if t[x]<0:
t[x]=0
wyn += int(t[x]/k)
if t[x]%k!=0:
if x!=len(t)-1:
t[x+1]+=t[x]%k
t_bool[x+1]=True
else:
wyn+=1
print(wyn)
```
| 104,444 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Tags: greedy
Correct Solution:
```
n,k=map(int,input().split())
arr=list(map(int,input().split()))
ans=arr[0]//k
val=arr[0]%k
for i in range(1,n):
if(val==0):
ans+=arr[i]//k
val=arr[i]%k
else:
val+=arr[i]
if(val<k):
val=0
ans+=1
else:
ans+=val//k
val=val%k
if(val!=0):
ans+=1
print(ans)
```
| 104,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Submitted Solution:
```
import math
def findMinBags(n, capacity, garbages):
bags = 0
must_bag = 0
remaining_space = 0
for garb in garbages:
if must_bag:
remaining_space = capacity - (must_bag % capacity)
bags += math.ceil(must_bag / capacity)
if garb >= remaining_space:
garb -= remaining_space
must_bag = garb % capacity
bags += garb // capacity
else:
must_bag = 0
remaining_space = 0
if must_bag: bags += 1
return bags
n, capacity = [int(x) for x in input().split(' ')]
garbages = [int(x) for x in input().split(' ')]
print(findMinBags(n, capacity, garbages))
```
Yes
| 104,446 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Submitted Solution:
```
n, k = map(int, input().split())
a = [int(x) for x in input().split()]
bags, r = 0, 0
for i in range(n):
x = a[i] + r
if x == 0:
continue
elif x < k and r > 0:
bags += 1
r = 0
else:
bags += (x // k)
r = (x % k)
if r > 0:
bags += 1
print(bags)
```
Yes
| 104,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Submitted Solution:
```
a,b=map(int,input().split())
s=0;p=0;y=0
for i in map(int,input().split()):
if p:
if p+i>=b:
k=i+p
p=0
r=k//b
s+=r
p=k-(r*b)
else:s+=1;p=0
else:
k=i//b
s+=k
p=i-(k*b)
print(s+(p!=0))
```
Yes
| 104,448 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Submitted Solution:
```
n,k =map(int,input().split())
a=[int(x) for x in input().split()]
bag=a[0]//k
remain=a[0]%k
for i in range(1,n):
tk=a[i]+remain
remain=tk%k
if remain>a[i]:
bag+=1
remain=0
else:
bag+=tk//k
if remain==0:
print(bag)
else:
print(bag+1)
```
Yes
| 104,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Submitted Solution:
```
import math
n, k = map(int, input().split())
a = list(map(int, input().split()))
cnt = 0
for i in range(n - 1):
cnt += a[i] // k
a[i] %= k
if i + 1 == n - 1:
a[i + 1] += a[i]
elif k - a[i] <= a[i+1]:
cnt += 1
a[i + 1] -= (k - a[i])
else:
cnt += math.ceil(a[i]/k) if a[i] else 0
cnt += math.ceil(a[-1]/k)
print(cnt)
```
No
| 104,450 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Submitted Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
res = 0
sum = 0
can = True
for i in range(n):
if can is False:
print('cc', sum)
sum = sum + a[i]
res = res + max(1, sum // m)
sum = sum % m
can = True
else:
sum = sum + a[i]
# print('ff', sum)
if sum > m:
res = res + sum // m
sum = sum % m
can = True
else:
print('dd', sum)
can = False
print(res)
```
No
| 104,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Submitted Solution:
```
n,k=map(int,input().split())
a=list(map(int,input().split()))
l=0
for i in range(len(a)-1):
if(a[i]+a[i+1]>=k):
l+=(a[i+1]+a[i])//k
a[i+1]=(a[i+1]+a[i])%k
else:
l+=1
a[i+1]=0
print(l)
```
No
| 104,452 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Submitted Solution:
```
n,k=map(int,input().split())
a=list(map(int,input().split()))
l=0
for i in range(len(a)-1):
if(a[i]+a[i+1]>=k):
l+=(a[i]+a[i+1])//k
a[i+1]=(a[i]+a[i+1])%k
else:
l+=1
a[i+1]=0
if(a[-1]>=k):
l+=a[-1]//k
else:
l+=1
print(l-1)
```
No
| 104,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define the Eulerian traversal of a tree (a connected undirected graph without cycles) as follows: consider a depth-first search algorithm which traverses vertices of the tree and enumerates them in the order of visiting (only the first visit of each vertex counts). This function starts from the vertex number 1 and then recursively runs from all vertices which are connected with an edge with the current vertex and are not yet visited in increasing numbers order. Formally, you can describe this function using the following pseudocode:
next_id = 1
id = array of length n filled with -1
visited = array of length n filled with false
function dfs(v):
visited[v] = true
id[v] = next_id
next_id += 1
for to in neighbors of v in increasing order:
if not visited[to]:
dfs(to)
You are given a weighted tree, the vertices of which were enumerated with integers from 1 to n using the algorithm described above.
A leaf is a vertex of the tree which is connected with only one other vertex. In the tree given to you, the vertex 1 is not a leaf. The distance between two vertices in the tree is the sum of weights of the edges on the simple path between them.
You have to answer q queries of the following type: given integers v, l and r, find the shortest distance from vertex v to one of the leaves with indices from l to r inclusive.
Input
The first line contains two integers n and q (3 ≤ n ≤ 500 000, 1 ≤ q ≤ 500 000) — the number of vertices in the tree and the number of queries, respectively.
The (i - 1)-th of the following n - 1 lines contains two integers p_i and w_i (1 ≤ p_i < i, 1 ≤ w_i ≤ 10^9), denoting an edge between vertices p_i and i with the weight w_i.
It's guaranteed that the given edges form a tree and the vertices are enumerated in the Eulerian traversal order and that the vertex with index 1 is not a leaf.
The next q lines describe the queries. Each of them contains three integers v_i, l_i, r_i (1 ≤ v_i ≤ n, 1 ≤ l_i ≤ r_i ≤ n), describing the parameters of the query. It is guaranteed that there is at least one leaf with index x such that l_i ≤ x ≤ r_i.
Output
Output q integers — the answers for the queries in the order they are given in the input.
Examples
Input
5 3
1 10
1 1
3 2
3 3
1 1 5
5 4 5
4 1 2
Output
3
0
13
Input
5 3
1 1000000000
2 1000000000
1 1000000000
1 1000000000
3 4 5
2 1 5
2 4 5
Output
3000000000
1000000000
2000000000
Input
11 8
1 7
2 1
1 20
1 2
5 6
6 2
6 3
5 1
9 10
9 11
5 1 11
1 1 4
9 4 8
6 1 4
9 7 11
9 10 11
8 1 11
11 4 5
Output
8
8
9
16
9
10
0
34
Note
In the first example, the tree looks like this:
<image>
In the first query, the nearest leaf for the vertex 1 is vertex 4 with distance 3. In the second query, the nearest leaf for vertex 5 is vertex 5 with distance 0. In the third query the nearest leaf for vertex 4 is vertex 4; however, it is not inside interval [1, 2] of the query. The only leaf in interval [1, 2] is vertex 2 with distance 13 from vertex 4.
Submitted Solution:
```
n, q = map(int, input().split())
children = [[]] * (n+1)
upiti = [[]] * (n+1)
hi = [0] * (n+1)
dub = [0] * (n+1)
ans = [10**18] * q
class Segmentno:
def __init__(self):
self.a = [0] * (2 * 524288)
self.b = [0] * (2 * 524288)
def push(self, x):
if x < 524288:
self.b[2*x] += self.b[x]
self.b[2*x + 1] += self.b[x]
self.a[x] += self.b[x]
self.b[x] = 0
def update_impl(self, l, r, v, x, xl, xr):
if r < xl or xr < l:
self.push(x)
return
if l <= xl and xr <= r:
self.b[x] += v
self.push(x)
return
xm = (xl + xr) // 2
self.push(x)
self.update_impl(l, r, v, 2*x, xl, xm)
self.update_impl(l, r, v, 2*x+1, xm+1, xr)
self.a[x] = min(self.a[2*x:2*x+2])
def update(self, l, r, v):
self.update_impl(l, r, v, 1, 1, 524288)
def get_impl(self, l, r, x, xl, xr):
self.push(x)
if r < xl or xr < l:
return 10 ** 18
if l <= xl and xr <= r:
return self.a[x]
xm = (xl + xr) // 2
return min([
self.get_impl(l, r, 2*x, xl, xm),
self.get_impl(l, r, 2*x+1, xm+1, xr)
])
def get(self, l, r):
return self.get_impl(l, r, 1, 1, 524288)
for i in range(2, n+1):
p, w = map(int, input().split())
if children[p] == []:
children[p] = []
children[p] += [(i, w)]
drvo = Segmentno()
def calc_hi(x):
hi[x] = x
for y, w in children[x]:
dub[y] = dub[x] + w
calc_hi(y)
hi[x] = hi[y]
calc_hi(1)
for i in range(1, n+1):
print(children[i])
if len(children[i]) > 0:
drvo.update(i, i, 10**18)
else:
drvo.update(i, i, dub[i])
for i in range(q):
x, l, r = map(int, input().split())
if upiti[x] == []:
upiti[x] = []
upiti[x] += [(l, r, i)]
def dfs(x):
for l, r, i in upiti[x]:
ans[i] = drvo.get(l, r)
for y, w in children[x]:
drvo.update(1, n, w)
drvo.update(y, hi[y], -w-w)
dfs(y)
drvo.update(y, hi[y], w+w)
drvo.update(1, n, -w)
dfs(1)
for x in ans:
print(x)
```
No
| 104,454 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Tags: brute force, data structures, sortings
Correct Solution:
```
from copy import deepcopy
class PriorityQueue():
def __init__(self):
self.elements = [(0, None)]
self.size = 0
self.capacity = 1000
def push(self, item):
# the first element of item is the index, it must be digits
self.size += 1
self.elements.append(item)
i = self.size
while self.elements[i//2][0]>item[0]:
self.elements[i] = self.elements[i//2]
i = i // 2
self.elements[i] = item
def poll(self):
if self.size <= 0:
return None
min_element = deepcopy(self.elements[1])
last_element = self.elements.pop()
self.size -= 1
i = 1
while (i*2)<=self.size:
child = i * 2 # left child
if (child != self.size and (self.elements[child+1][0] < self.elements[child][0])):
child += 1
if last_element[0] > self.elements[child][0]:
self.elements[i] = self.elements[child]
else:
break
i = child
if self.size > 0:
self.elements[i] = last_element
return min_element
import heapq
n,k = tuple(map(int, input().split(' ')))
s = []
for i in range(n):
t = tuple(map(int, input().split(' ')))
s.append(t)
def get_beauty(e):
return e[1]
s.sort(reverse=True, key=get_beauty)
max_score = 0
sum_len = 0
heap = []
try:
for i in range(n):
length = s[i][0]
beauty = s[i][1]
heapq.heappush(heap,length)
sum_len += length
if i+1 > k:
sum_len-=heapq.heappop(heap)
score = (sum_len) * beauty
max_score = max(max_score, score)
except Exception as e:
print(e)
print(max_score)
```
| 104,455 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Tags: brute force, data structures, sortings
Correct Solution:
```
import sys
import heapq
input = sys.stdin.readline
n, k = map(int, input().split())
l = []
for i in range(n):
a, b = map(int, input().split())
l.append((a,b))
l.sort(key = lambda x: x[1], reverse = True)
best = 0
curr = 0
q = []
for i in range(k):
curr += l[i][0]
heapq.heappush(q,l[i][0])
best = max(best, curr * l[i][1])
for i in range(k,n):
curr += l[i][0]
heapq.heappush(q,l[i][0])
curr -= heapq.heappop(q)
best = max(best, curr * l[i][1])
print(best)
```
| 104,456 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Tags: brute force, data structures, sortings
Correct Solution:
```
#import resource
import sys
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
mod=(10**9)+7
#fact=[1]
#for i in range(1,1001):
# fact.append((fact[-1]*i)%mod)
#ifact=[0]*1001
#ifact[1000]=pow(fact[1000],mod-2,mod)
#for i in range(1000,0,-1):
# ifact[i-1]=(i*ifact[i])%mod
from sys import stdin, stdout
#from bisect import bisect_left as bl
#from bisect import bisect_right as br
#import itertools
#import math
#import heapq
#from random import randint as rn
#from Queue import Queue as Q
def modinv(n,p):
return pow(n,p-2,p)
def ncr(n,r,p):
t=((fact[n])*((ifact[r]*ifact[n-r])%p))%p
return t
def ain():
return list(map(int,sin().split()))
def sin():
return stdin.readline()
def GCD(x, y):
while(y):
x, y = y, x % y
return x
"""**************************************************************************"""
def merge1(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
L = [0 for i in range(n1)]
R = [0 for i in range(n2)]
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
i,j,k=0,0,l
while i < n1 and j < n2 :
if L[i][1] < R[j][1]:
arr[k] = L[i]
i += 1
elif L[i][1] > R[j][1]:
arr[k] = R[j]
j += 1
else:
if L[i][0] < R[j][0]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def mergesort1(arr,l,r):
if l < r:
m = (l+(r-1))//2
mergesort1(arr, l, m)
mergesort1(arr, m+1, r)
merge1(arr, l, m, r)
def merge2(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
L = [0 for i in range(n1)]
R = [0 for i in range(n2)]
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
i,j,k=0,0,l
while i < n1 and j < n2 :
if L[i][0] > R[j][0]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def mergesort2(arr,l,r):
if l < r:
m = (l+(r-1))//2
mergesort2(arr, l, m)
mergesort2(arr, m+1, r)
merge2(arr, l, m, r)
n,k=ain()
b=[]
for i in range(n):
b.append(ain())
mergesort1(b,0,n-1)
r=[]
for i in range(n):
r.append([b[i][0],i])
mergesort2(r,0,n-1)
g=[0 for i in range(n)]
s=0
for i in range(k):
s+=r[i][0]
g[r[i][1]]=1
p=k
s1=0
for i in range(n):
q=s*b[i][1]
s1=max(s1,q)
if(g[i]==1):
s-=b[i][0]
while(p<n):
if(r[p][1]>i):
s+=r[p][0]
g[r[p][1]]=1
p+=1
break
p+=1
print (s1)
```
| 104,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Tags: brute force, data structures, sortings
Correct Solution:
```
from heapq import heappush, heappop
N, K = [int(s) for s in input().split()]
songs = []
for _ in range(N):
t, b = [int(s) for s in input().split()]
songs.append((t, b))
songs.sort(key= lambda x: x[1], reverse=True)
max_pleasure = 0
total_length = 0
max_lengths = []
for i in range(K):
total_length += songs[i][0]
heappush(max_lengths, songs[i][0])
max_pleasure = max(max_pleasure, total_length * songs[i][1])
for i in range(K, N):
if max_lengths[0] < songs[i][0]:
min_length = heappop(max_lengths)
heappush(max_lengths, songs[i][0])
total_length = total_length - min_length + songs[i][0]
max_pleasure = max(max_pleasure, total_length * songs[i][1])
print(max_pleasure)
```
| 104,458 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Tags: brute force, data structures, sortings
Correct Solution:
```
# -*- coding: utf-8 -*-
# @Date : 2019-03-23 09:28:20
# @Author : raj lath (oorja.halt@gmail.com)
# @Link : link
# @Version : 1.0.0
import sys
import heapq
sys.setrecursionlimit(10**5+1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
nb_songs, choose = RMI()
songval = []
for _ in range(nb_songs):
songval.append(RMI())
songval.sort(key = lambda x: -x[1])
maxs = min_val
lsum = 0
choice = []
for i in range(nb_songs):
ti, bi = songval[i]
if len(choice) < choose:
heapq.heappush(choice, ti)
lsum += ti
else:
l = heapq.heappushpop(choice, ti)
lsum += ti - l
maxs = max(maxs, lsum * bi)
print(maxs)
```
| 104,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Tags: brute force, data structures, sortings
Correct Solution:
```
import heapq
arr = input()
N,K = [int(x) for x in arr.split(' ')]
data = [[0]*2 for _ in range(N)]
for i in range(N):
arr = input()
L,B = [int(x) for x in arr.split(' ')]
data[i][0] = B
data[i][1] = L
data.sort(reverse=True)
#print(data)
h = []
s = 0
res = 0
for i in range(N):
if i<K:
s += data[i][1]
heapq.heappush(h, data[i][1])
else:
s += data[i][1]
heapq.heappush(h, data[i][1])
p = heapq.heappop(h)
s -= p
if s*data[i][0]>res:
res = s*data[i][0]
print(res)
```
| 104,460 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Tags: brute force, data structures, sortings
Correct Solution:
```
import heapq
d=[]
n,k=[int(x) for x in input().split()]
c=[]
lena=0
for i in range(n):
a,b=[int(x) for x in input().split()]
c.append((b,a))
c.sort(reverse=True)
answer=[]
summa=0
for item in c:
if lena>=k:
a=heapq.heappop(d)
summa-=a
heapq.heappush(d,max(item[1],a))
summa+=max(item[1],a)
else:
heapq.heappush(d,item[1])
summa+=item[1]
lena+=1
answer.append(summa*item[0])
print(max(answer))
```
| 104,461 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Tags: brute force, data structures, sortings
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from heapq import *
n,k=map(int,input().split())
a=[]
for i in range(n):
y,x=map(int,input().split())
a.append([x,y])
a.sort(reverse=True)
ans=0
s=0
hp=[]
for i in range(n):
s+=a[i][1]
heappush(hp,a[i][1])
if i>=k :
s-=heappop(hp)
ans=max(ans,a[i][0]*s)
print(ans)
```
| 104,462 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Submitted Solution:
```
from heapq import *
n,k=list(map(int,input().split()))
a=[]
for i in range(0,n):
b,p=list(map(int,input().split()))
a.append([p,b])
a.sort(reverse=True)
r=0
s=0
h=[]
for p,b in a:
s+=b
heappush(h,b)
if len(h)>k:
s-=heappop(h)
r=max(r,s*p)
print(r)
```
Yes
| 104,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Submitted Solution:
```
from heapq import heappush, heappop
heapObj = []
n,k = map(int, input().strip().split())
l = []
for i in range(n):
t,b = map(int, input().strip().split())
l.append([b,t])
l.sort()
ct = 0
ans = 0
sm = 0
for i in range(n-1,-1,-1):
if ct < k:
ct += 1
sm += l[i][1]
heappush(heapObj, l[i][1])
else:
mn = heapObj[0]
if l[i][1] > mn:
heappop(heapObj)
heappush(heapObj,l[i][1])
sm = sm - mn + l[i][1]
ans = max(ans,l[i][0]*sm)
print(ans)
```
Yes
| 104,464 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Submitted Solution:
```
from heapq import heappop, heappush
n, k = map(int, input().split())
d = []
for i in range(n):
t, b = map(int, input().split())
d.append((t, b))
d = sorted(d, key=lambda x: (x[1], x[0]), reverse=True)
num = 0
tmp = []
tmp2 = 0
for i in range(n):
num = max(num, (tmp2 + d[i][0]) * d[i][1])
heappush(tmp, d[i][0])
tmp2 += d[i][0]
if len(tmp) > k - 1:
tmp2 -= heappop(tmp)
print(num)
```
Yes
| 104,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Submitted Solution:
```
from heapq import heappush,heappop
n,k=map(int,input().split())
a=[]
for i in range(n):
x,y=map(int,input().split())
a.append([y,x])
a.sort(reverse=True)
h=[]
ans,sm=0,0
for b,l in a:
sm+=l
heappush(h,l)
if len(h)>k:
sm-=heappop(h)
ans=max(ans,sm*b)
print(ans)
```
Yes
| 104,466 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Submitted Solution:
```
n,k=map(int,input().split())
a=[]
for _ in range(n):
t=list(map(int,input().split()))
a.append(t)
a=sorted(a,key=lambda x: x[1])
ma=0
for i in range(n):
if(a[i][0]*a[i][1]>ma):
ma=a[i][0]*a[i][1]
p=i
su=a[p][0]
c=a[p][1]
ans=su*c
co=1
mi=a[p][0]
ans1=[]
for i in range(n):
if(n-1-i!=p):
if(((su+a[n-1-i][0])*a[n-1-i][1])>ans and co<k):
su+=a[n-1-i][0]
if(a[n-1-i][1]<c):
c=a[n-1-i][1]
ans=su*c
co+=1
ans1.append(a[n-1-i][0])
mi=min(ans1)
elif(co>=k):
if(((su+a[n-1-i][0]-mi)*a[n-1-i][1])>ans):
su+=a[n-1-i][0]
su-=mi
if(a[n-1-i][1]<c):
c=a[n-1-i][1]
ans=su*c
ans1.append(a[n-1-i][0])
ans1.remove(mi)
mi=min(ans1)
print(ans)
```
No
| 104,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Submitted Solution:
```
from sys import stdin
import heapq as hp
n,k=map(int,stdin.readline().strip().split())
s=[]
for i in range(n):
a,b=map(int,stdin.readline().strip().split())
s.append((b,a))
s.sort(reverse=True)
s1=[]
s2=[]
sm=0
mx=-10**7
mn=10**7
ans=0
for i in range(k):
sm+=s[i][1]
hp.heappush(s1,s[i][1])
ans=max(sm*s[i][0],ans)
for i in range(k+1,n):
x=hp.heappop(s1)
if s[i][1]>x:
sm-=x
sm+=s[i][1]
hp.heappush(s1,s[i][1])
else:
hp.heappush(s1,x)
ans=max(ans,sm*s[i][0])
print(ans)
```
No
| 104,468 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Submitted Solution:
```
songs = []
n, k = map(int, input().split())
for i in range(n):
a, b = map(int, input().split())
songs.append([b, a])
songs.sort(key=lambda p: (-p[0] * p[1], p[0], p[1]))
minn = 10 ** 7
nice = 10 ** 7
summ = 0
maxsum = 0
i = 0
while i <= k:
summ += songs[i][1]
nice = min(songs[i][0], nice)
maxsum = max(maxsum, summ * nice)
i += 1
print(maxsum)
```
No
| 104,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Submitted Solution:
```
songs=[]
effect=[]
n,k=list(map(int,input().split()))
for i in range(n):
t,b=list(map(int,input().split()))
songs.append((t,b))
songs.sort(key=lambda x:x[1])
for i in range(k):
l=[]
for j in range(i+1):
l.append(songs[len(songs)-j-1][0])
effect.append(sum(l)*songs[len(songs)-i-1][1])
print(max(effect))
```
No
| 104,470 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Tags: implementation, math
Correct Solution:
```
n=int(input())
s=input()
ini=0
sta=0
for i in range(n):
if s[i]=="-":
if sta==0:
ini+=1
else:
sta-=1
if s[i]=="+":
sta+=1
print(sta)
```
| 104,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Tags: implementation, math
Correct Solution:
```
op = int(input())
pile=input()
a=pile[0]
if a=='-':
stone=1
else:
stone=0
for i in range(op):
if pile[i]=='+':
stone+=1
else:
stone-=1
if stone<0:
stone=0
print(stone)
```
| 104,472 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Tags: implementation, math
Correct Solution:
```
num = int(input())
string=str(input())
total=0
for counter,item in enumerate(string):
if item=="-" and total==0:
continue
elif item=="-" and total!=0:
total=total-1
elif item=="+":
total=total+1
print(total)
```
| 104,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Tags: implementation, math
Correct Solution:
```
n = int(input())
s = input()
ans = 0
for i in range(n):
ans = max(ans, s[i:].count("+")-s[i:].count("-"))
print(ans)
```
| 104,474 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Tags: implementation, math
Correct Solution:
```
def rahul(word):
return[char for char in word]
a=int(input())
b=rahul(input())
r=0
s=0
while r<a:
if b[r]=='+':
s=s+1
elif b[r]=='-' and s>0:
s=s-1
r=r+1
print(s)
```
| 104,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Tags: implementation, math
Correct Solution:
```
n = int(input())
a = input()
res = 0
for i in range(n):
if a[i] == '-':
res -= 1
elif a[i] == '+':
if res < 0:
res = 1
else:
res += 1
if res < 0:
res = 0
print(res)
```
| 104,476 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Tags: implementation, math
Correct Solution:
```
def run_commands(start, cmd):
for c in cmd:
if c == "-":
start -= 1
#print("subtracted to", start)
elif c == "+":
start += 1
if start < 0:
return False
return start
n = int(input())
cmd = list(input())
for start in range(0, 101):
result = run_commands(start, cmd)
if result is False:
continue
else:
print(result)
break
```
| 104,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Tags: implementation, math
Correct Solution:
```
n = int(input())
s = input()
p = False
x = 0
for i in range(n):
if not p and s[i] == "+":
p = True
if p:
if s[i] == "+":
x += 1
else:
if x > 0:
x -= 1
print(x)
```
| 104,478 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Submitted Solution:
```
# -*- coding: utf-8 -*-
# @Time : 2019/5/12 22:46
# @Author : LunaFire
# @Email : gilgemesh2012@gmail.com
# @File : A. A pile of stones.py
def main():
n = int(input())
s = input()
ret = 0
for c in s:
if c == '-':
ret = max(0, ret - 1)
else:
ret += 1
print(ret)
if __name__ == '__main__':
main()
```
Yes
| 104,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Submitted Solution:
```
n = int(input())
s = input()
minim = n
maxim = 0
for ch in s:
if ch == '-':
n -= 1
else:
n += 1
minim = min(minim, n)
print(n - minim)
```
Yes
| 104,480 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Submitted Solution:
```
n=int(input())
s=input()
c=0
d=0
for i in s:
if(i=="-"):
if(c>0):
c=c-1
else:
c=c+1
print(c)
```
Yes
| 104,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Submitted Solution:
```
n = int(input())
s = input()
ans = 0
for c in s:
if c == '-':
ans -= ans != 0
else:
ans += 1
print(ans)
```
Yes
| 104,482 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Submitted Solution:
```
n=int(input())
s=input()
p=0
if(s[0]=='-'):
p+=1
a=s.count('+')
m=s.count('-')
if(a-m>=0):
print(p+a-m)
else:
print(0)
```
No
| 104,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Submitted Solution:
```
n= int(input())
p=input()[:n]
c=0
j=0
for i in p:
if i=='+':
c+=1
elif i=='-':
j+=1
if p[0]=='+':
n=0
elif p[0]=='-'and p[1]=='+' and c>=j:
n=1
for k in p:
if(k=='+'):
n+=1
elif(k=='-'):
n-=1
print(n)
```
No
| 104,484 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Submitted Solution:
```
n = int(input())
s = input()
m = n
for ch in s:
if (ch == '-'):
n -= 1
else:
n += 1
m = min(m, n)
print(m)
```
No
| 104,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Submitted Solution:
```
#!/usr/bin/env python3
n = int(input())
opers = input()
k = 100
for i in opers:
if i == '+':
k += 1
elif i == '-':
k -= 1
k = 100 - k
if k > 0:
if n - k == 0:
print(0)
else:
print(n - k)
else:
print(abs(k))
```
No
| 104,486 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Tags: greedy, math
Correct Solution:
```
x,y,z=map(int,input().split())
print((x+y)//z,end=" ")
a=x%z
b=y%z
if a+b>=z:
print(z-max(a,b))
else:
print("0")
```
| 104,487 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Tags: greedy, math
Correct Solution:
```
x, y, z = [int(i) for i in input().split()]
ans = 0
al = (x + y) // z
if x // z + y // z == al:
print(al, 0)
else:
print(al, min(z - (x % z), z - (y % z)))
```
| 104,488 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Tags: greedy, math
Correct Solution:
```
n,m,k = map(int,input().split())
a = n%k
if a:
a = k-a
b = m%k
if b:
b = k-b
if ((n+a)//k + (m-a)//k) > ((n-b)//k + (m+b)//k):
if ((n+a)//k + (m-a)//k) == (n//k + m//k):
print(((n+a)//k + (m-a)//k),0)
else:
print(((n+a)//k + (m-a)//k),a)
elif ((n+a)//k + (m-a)//k) == ((n-b)//k + (m+b)//k):
if (n+a)//k + (m-a)//k == (n//k + m//k):
print((n//k + m//k),0)
elif a>b:
print(((n-b)//k + (m+b)//k),b)
else:
print(((n-b)//k + (m+b)//k),a)
else:
if (n//k + m//k) == ((n-b)//k + (m+b)//k):
print(((n-b)//k + (m+b)//k),0)
else:
print(((n-b)//k + (m+b)//k),b)
```
| 104,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Tags: greedy, math
Correct Solution:
```
Input=lambda:map(int,input().split())
x,y,z = Input()
print((x+y)//z,end = " ")
Coconut = x//z
x%=z
Coconut += y//z
y%=z
r = (x+y)//z
Coconut+=r
if r == 0:
print(0)
else:
print(min(x,y)-((x+y)%z))
'''
openvpn
vpnbook
sEN6DC9
'''
```
| 104,490 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Tags: greedy, math
Correct Solution:
```
x,y,z = map(int , input().split())
temp = (x+y)//z
a = z-(x%z)
b = z-(y%z)
if temp == x//z + y//z :
print("{} 0".format(temp))
else:
temp2 = min(a,b)
print("{} {}".format(temp , temp2))
```
| 104,491 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Tags: greedy, math
Correct Solution:
```
x, y, z = list(map(int,input().split()))
# no_of_coconuts = (x//z) + (y//z)
no_of_coconuts = (x+y) // z
x_money_left = x % z
y_money_left = y % z
minimum = min(x_money_left,y_money_left)
maximum = max(x_money_left,y_money_left)
coconut = (maximum + minimum) //z
if coconut == 0:
print(no_of_coconuts, 0)
else:
coconut_price = (coconut * z) - maximum
print(no_of_coconuts, coconut_price)
```
| 104,492 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Tags: greedy, math
Correct Solution:
```
# Chunga-Changa
# from collections import Counter
x, y, z = list(map(int, input().split()))
max_coc = (x + y) // z
if (x // z) + (y // z) == max_coc:
give = 0
else:
r1 = x % z
r2 = y % z
give = min(r1, r2, z - r1, z - r2)
print(max_coc, give)
```
| 104,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Tags: greedy, math
Correct Solution:
```
x,y,z = list(map(int,input().split()))
if x%z+y%z<z: #если за остатки можно купить кокос
print(x//z+y//z,0)
else:
if x%z>=y%z:print(x//z+y//z+1,z-x%z)
else:print(x//z+y//z+1,z-y%z)
```
| 104,494 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Submitted Solution:
```
x, y, z = [int(i) for i in input().split()]
m = (x + y) // z
if x // z + y // z == m:
print(m, 0)
else:
print(m, min(z - x % z, z - y % z))
```
Yes
| 104,495 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Submitted Solution:
```
X, Y, Z = map(int, input().split())
a = (X+Y)//Z
n = X//Z + Y//Z
if a == n:
b = 0
else:
b = min(Z-X%Z, Z-Y%Z)
print(a,b)
```
Yes
| 104,496 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Submitted Solution:
```
x, y, z = [int(i) for i in input().split()]
totalCoco = (x+y)//z
sashaCoco = x//z
mashaCoco = y//z
if sashaCoco + mashaCoco == totalCoco:
print(totalCoco, 0)
else:
print(totalCoco, z-max(x % z, y % z))
```
Yes
| 104,497 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Submitted Solution:
```
x,y,z = map(int,input().split());
re1 = x%z;
re2 = y%z;
no = x//z + y//z;
if(re1+re2<z):
print(str(no)+" 0");
else:
if(re1>=re2):
res = z - re1;
no=no+1;
print(str(no)+" "+str(res));
else:
res = z - re2;
no=no+1;
print(str(no)+" "+str(res));
```
Yes
| 104,498 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Submitted Solution:
```
x,y,z=(int(x) for x in input().split())
coconut=int(x/z)+int(y/z)
sasha_rem=x%z
masha_rem=y%z
rem_coconut=int((sasha_rem+masha_rem)/z)
if rem_coconut!=0:
coconut+=rem_coconut
sasha_rem=z-sasha_rem
masha_rem=z-masha_rem
if sasha_rem>masha_rem:
print(coconut,masha_rem)
else:
print(coconut,sasha_rem)
else:
print(coconut, 0)
```
No
| 104,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.