message stringlengths 2 45.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 254 108k | cluster float64 3 3 | __index_level_0__ int64 508 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people standing on the x-axis. Let the coordinate of Person i be x_i. For every i, x_i is an integer between 0 and 10^9 (inclusive). It is possible that more than one person is standing at the same coordinate.
You will given M pieces of information regarding the positions of these people. The i-th piece of information has the form (L_i, R_i, D_i). This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.
It turns out that some of these M pieces of information may be incorrect. Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.
Constraints
* 1 \leq N \leq 100 000
* 0 \leq M \leq 200 000
* 1 \leq L_i, R_i \leq N (1 \leq i \leq M)
* 0 \leq D_i \leq 10 000 (1 \leq i \leq M)
* L_i \neq R_i (1 \leq i \leq M)
* If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).
* D_i are integers.
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M
Output
If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print `Yes`; if it does not exist, print `No`.
Examples
Input
3 3
1 2 1
2 3 1
1 3 2
Output
Yes
Input
3 3
1 2 1
2 3 1
1 3 5
Output
No
Input
4 3
2 1 1
2 3 5
3 4 2
Output
Yes
Input
10 3
8 7 100
7 9 100
9 8 100
Output
No
Input
100 0
Output
Yes
Submitted Solution:
```
import sys
sys.setrecursionlimit(100010)
pos = [[] for i in range(600010)]
por = [[] for s in range(600010)]
posvis = [1 for y in range(600010)]
qe = []
n, m = map(int, input().split())
for i in range(m):
l, r, d = map(int, input().split())
pos[l].append([r, d, i])
pos[r].append([l, -d, i])
qe.append([l, r, i])
def deep(self):
for j in pos[self]:
if posvis[j[2]]:
posvis[j[2]] = 0
if len(por[self]) < 1:
por[self] = [100000]
if len(set(por[self])) > 1:
print("No")
exit()
por[j[0]].append(por[self][0] + j[1])
por[j[0]] = list(set(por[j[0]]))
if len(set(por[j[0]])) > 1:
print("No")
exit()
deep(j[0])
for qww in qe:
if posvis[qww[2]]:
deep(qww[0])
for i in por:
if i:
if len(set(i)) > 1:
print("No")
exit()
else:
print("Yes")
``` | instruction | 0 | 73,164 | 3 | 146,328 |
No | output | 1 | 73,164 | 3 | 146,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people standing on the x-axis. Let the coordinate of Person i be x_i. For every i, x_i is an integer between 0 and 10^9 (inclusive). It is possible that more than one person is standing at the same coordinate.
You will given M pieces of information regarding the positions of these people. The i-th piece of information has the form (L_i, R_i, D_i). This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.
It turns out that some of these M pieces of information may be incorrect. Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.
Constraints
* 1 \leq N \leq 100 000
* 0 \leq M \leq 200 000
* 1 \leq L_i, R_i \leq N (1 \leq i \leq M)
* 0 \leq D_i \leq 10 000 (1 \leq i \leq M)
* L_i \neq R_i (1 \leq i \leq M)
* If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).
* D_i are integers.
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M
Output
If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print `Yes`; if it does not exist, print `No`.
Examples
Input
3 3
1 2 1
2 3 1
1 3 2
Output
Yes
Input
3 3
1 2 1
2 3 1
1 3 5
Output
No
Input
4 3
2 1 1
2 3 5
3 4 2
Output
Yes
Input
10 3
8 7 100
7 9 100
9 8 100
Output
No
Input
100 0
Output
Yes
Submitted Solution:
```
from collections import deque
N,M = map(int,input().split())
A = [[] for i in range(N)]
for i in range(M) :
l,r,d = map(int,input().split())
l -= 1
r -= 1
A[l].append([r,d])
A[r].append([l,-d])
dist = [False for i in range(N)]
ans = "Yes"
flg1 = 0
flg2 = 0
for i in range(N) :
if flg1 :
break
if dist[i] :
continue
dist[i] = 0
q = deque([i])
while q :
if flg2 :
break
now = q.pop()
for to,d in A[now] :
if not dist[to] :
dist[to] = dist[now] + d
q.append(to)
elif dist[to] == dist[now] + d :
continue
else :
ans = "No"
flg1 = 1
flg2 = 1
break
print(ans)
``` | instruction | 0 | 73,165 | 3 | 146,330 |
No | output | 1 | 73,165 | 3 | 146,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people standing on the x-axis. Let the coordinate of Person i be x_i. For every i, x_i is an integer between 0 and 10^9 (inclusive). It is possible that more than one person is standing at the same coordinate.
You will given M pieces of information regarding the positions of these people. The i-th piece of information has the form (L_i, R_i, D_i). This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.
It turns out that some of these M pieces of information may be incorrect. Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.
Constraints
* 1 \leq N \leq 100 000
* 0 \leq M \leq 200 000
* 1 \leq L_i, R_i \leq N (1 \leq i \leq M)
* 0 \leq D_i \leq 10 000 (1 \leq i \leq M)
* L_i \neq R_i (1 \leq i \leq M)
* If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).
* D_i are integers.
Input
Input is given from Standard Input in the following format:
N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M
Output
If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print `Yes`; if it does not exist, print `No`.
Examples
Input
3 3
1 2 1
2 3 1
1 3 2
Output
Yes
Input
3 3
1 2 1
2 3 1
1 3 5
Output
No
Input
4 3
2 1 1
2 3 5
3 4 2
Output
Yes
Input
10 3
8 7 100
7 9 100
9 8 100
Output
No
Input
100 0
Output
Yes
Submitted Solution:
```
import sys
sys.setrecursionlimit(1000000)
n, m = map(int,input().split())
a = [[] for _ in range(n)]
for _ in range(m):
l, r, d = map(int,input().split())
a[l-1].append((r-1,d))
a[r-1].append((l-1,-d))
x = [None for _ in range(n)]
def check(y):
for z,d in a[y]:
if x[z] is None:
x[z] = x[y] + d
return check(z)
elif x[z] != x[y] + d:
return False
return True
for i in range(n):
if x[i] is None:
x[i] = 0
if not check(i):
print('No')
exit(0)
print('Yes')
``` | instruction | 0 | 73,166 | 3 | 146,332 |
No | output | 1 | 73,166 | 3 | 146,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N oases on a number line. The coordinate of the i-th oases from the left is x_i.
Camel hopes to visit all these oases. Initially, the volume of the hump on his back is V. When the volume of the hump is v, water of volume at most v can be stored. Water is only supplied at oases. He can get as much water as he can store at a oasis, and the same oasis can be used any number of times.
Camel can travel on the line by either walking or jumping:
* Walking over a distance of d costs water of volume d from the hump. A walk that leads to a negative amount of stored water cannot be done.
* Let v be the amount of water stored at the moment. When v>0, Camel can jump to any point on the line of his choice. After this move, the volume of the hump becomes v/2 (rounded down to the nearest integer), and the amount of stored water becomes 0.
For each of the oases, determine whether it is possible to start from that oasis and visit all the oases.
Constraints
* 2 ≤ N,V ≤ 2 × 10^5
* -10^9 ≤ x_1 < x_2 < ... < x_N ≤ 10^9
* V and x_i are all integers.
Input
Input is given from Standard Input in the following format:
N V
x_1 x_2 ... x_{N}
Output
Print N lines. The i-th line should contain `Possible` if it is possible to start from the i-th oasis and visit all the oases, and `Impossible` otherwise.
Examples
Input
3 2
1 3 6
Output
Possible
Possible
Possible
Input
7 2
-10 -4 -2 0 2 4 10
Output
Impossible
Possible
Possible
Possible
Possible
Possible
Impossible
Input
16 19
-49 -48 -33 -30 -21 -14 0 15 19 23 44 52 80 81 82 84
Output
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Impossible
Impossible
Impossible
Impossible
Submitted Solution:
```
import copy
from functools import reduce
def jumps(vol):
j = 0
while vol > 0:
vol = vol // 2
j += 1
return j
def visitable(oases, i, vol):
return visitable_r(oases, i, vol, [False] * len(oases))
def visitable_r(oases, i, vol, visited):
# visit all visitable by sliding
visited[i] = True
# print("i: ", i, " vol: ", vol)
# print(visited)
j = i + 1
while j < len(oases) and (oases[j] - oases[j-1] <= vol):
visited[j] = True
j += 1
j = i - 1
while j >= 0 and (oases[j+1] - oases[j] <= vol):
visited[j] = True
j -= 1
# print("spread: ", visited)
if reduce((lambda x, y: x and y), visited):
return True
if vol == 0:
return False
if not checkMaybeViable(visited, vol):
return False
unvisited = 0
for j in range(len(oases)):
if not visited[j]:
unvisited += 1
if visitable_r(oases, j, vol//2, copy.copy(visited)):
return True
return unvisited == 0
def checkMaybeViable(visited, vol):
jump = jumps(vol)
isles = 0
lastNeedToVisit = 0
for i in range(len(visited)):
if i == 0 or ((oases[i] - lastNeedToVisit > vol) and (not visited[i])):
lastNeedToVisit = oases[i]
isles += 1
if isles > jump + 1:
return False
return True
# [n, vol] = list(map(lambda x: int(x), "16 19".split()))
# oases = list(map(lambda x: int(x), "-49 -48 -33 -30 -21 -14 0 15 19 23 44 52 80 81 82 84".split()))
[n, vol] = list(map(lambda x: int(x), input().split()))
oases = list(map(lambda x: int(x), input().split()))
for i in range(n):
if visitable(oases, i, vol):
print("Possible")
else:
print("Impossible")
``` | instruction | 0 | 73,183 | 3 | 146,366 |
No | output | 1 | 73,183 | 3 | 146,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N oases on a number line. The coordinate of the i-th oases from the left is x_i.
Camel hopes to visit all these oases. Initially, the volume of the hump on his back is V. When the volume of the hump is v, water of volume at most v can be stored. Water is only supplied at oases. He can get as much water as he can store at a oasis, and the same oasis can be used any number of times.
Camel can travel on the line by either walking or jumping:
* Walking over a distance of d costs water of volume d from the hump. A walk that leads to a negative amount of stored water cannot be done.
* Let v be the amount of water stored at the moment. When v>0, Camel can jump to any point on the line of his choice. After this move, the volume of the hump becomes v/2 (rounded down to the nearest integer), and the amount of stored water becomes 0.
For each of the oases, determine whether it is possible to start from that oasis and visit all the oases.
Constraints
* 2 ≤ N,V ≤ 2 × 10^5
* -10^9 ≤ x_1 < x_2 < ... < x_N ≤ 10^9
* V and x_i are all integers.
Input
Input is given from Standard Input in the following format:
N V
x_1 x_2 ... x_{N}
Output
Print N lines. The i-th line should contain `Possible` if it is possible to start from the i-th oasis and visit all the oases, and `Impossible` otherwise.
Examples
Input
3 2
1 3 6
Output
Possible
Possible
Possible
Input
7 2
-10 -4 -2 0 2 4 10
Output
Impossible
Possible
Possible
Possible
Possible
Possible
Impossible
Input
16 19
-49 -48 -33 -30 -21 -14 0 15 19 23 44 52 80 81 82 84
Output
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Possible
Impossible
Impossible
Impossible
Impossible
Submitted Solution:
```
import copy
from functools import reduce
def jumps(vol):
j = 0
while vol > 0:
vol = vol // 2
j += 1
return j
def visitable(oases, i, vol):
return visitable_r(oases, i, vol, [False] * len(oases))
def visitable_r(oases, i, vol, visited):
# visit all visitable by sliding
visited[i] = True
# print("i: ", i, " vol: ", vol)
# print(visited)
j = i + 1
while j < len(oases) and (oases[j] - oases[j-1] <= vol):
visited[j] = True
j += 1
j = i - 1
while j >= 0 and (oases[j+1] - oases[j] <= vol):
visited[j] = True
j -= 1
# print("spread: ", visited)
if reduce((lambda x, y: x and y), visited):
return True
if not checkMaybeViable(visited, vol):
return False
unvisited = 0
for j in range(len(oases)):
if not visited[j]:
unvisited += 1
if visitable_r(oases, j, vol//2, copy.copy(visited)):
return True
return unvisited == 0
def checkMaybeViable(visited, vol):
jump = jumps(vol)
isles = 0
lastNeedToVisit = 0
for i in range(len(visited)):
if i == 0 or ((oases[i] - lastNeedToVisit > vol) and (not visited[i])):
lastNeedToVisit = oases[i]
isles += 1
if isles > jump + 1:
return False
return True
[n, vol] = list(map(lambda x: int(x), input().split()))
oases = list(map(lambda x: int(x), input().split()))
for i in range(n):
if visitable(oases, i, vol):
print("Possible")
else:
print("Impossible")
``` | instruction | 0 | 73,184 | 3 | 146,368 |
No | output | 1 | 73,184 | 3 | 146,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of test cases.
The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≤ a, b, c ≤ 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.
Output
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
Example
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
Submitted Solution:
```
t=int(input())
s=[]
for ikofk in range(0,t):
x=input()
xx=x.split( )
for i in range(0,3):
xx[i]=int(xx[i])
xx.sort()
a=xx[0]
b=xx[1]
c=xx[2]
if c-a==0 or c-a==1 or c-a==2:
s.append(0)
else:
d=(c-a)+(c-b)+(b-a)-4
s.append(d)
for i in s:
print(i)
``` | instruction | 0 | 73,434 | 3 | 146,868 |
Yes | output | 1 | 73,434 | 3 | 146,869 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of test cases.
The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≤ a, b, c ≤ 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.
Output
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
Example
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
Submitted Solution:
```
import math
n = int(input())
for i in range(n):
a, b, c = sorted(list(map(int, input().split())))
t = math.floor((a + c) / 2)
if t > a:
a += 1
elif t < a:
a -= 1
if t > b:
b += 1
elif t < b:
b -= 1
if t > c:
c += 1
elif t < c:
c -= 1
print((b - a) + (c - b) + (c - a))
``` | instruction | 0 | 73,435 | 3 | 146,870 |
Yes | output | 1 | 73,435 | 3 | 146,871 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of test cases.
The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≤ a, b, c ≤ 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.
Output
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
Example
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
Submitted Solution:
```
q = int(input())
for p in range (q):
a, b, c = map(int,input().split())
r = max(a, b, c) - min(a, b, c)
if r > 1:
print((r-2) * 2)
else:
print(0)
``` | instruction | 0 | 73,436 | 3 | 146,872 |
Yes | output | 1 | 73,436 | 3 | 146,873 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of test cases.
The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≤ a, b, c ≤ 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.
Output
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
Example
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
Submitted Solution:
```
t=int(input())
for i in range(t):
a, b, c = input().split()
a=int(a)
b=int(b)
c=int(c)
d=max(a,b,c)
e=min(a,b,c)
if (d-e)>=2:
print(2*(d-e)-4)
else :
print(0)
``` | instruction | 0 | 73,437 | 3 | 146,874 |
Yes | output | 1 | 73,437 | 3 | 146,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of test cases.
The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≤ a, b, c ≤ 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.
Output
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
Example
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
Submitted Solution:
```
if __name__ == '__main__':
n=int(input())
while(n>0):
l = [int(x) for x in input().split()]
a=l[0]
b=l[1]
c=l[2]
list2=[]
list2.append(abs(a-b)+abs(a-c)+abs(b-c)) #2
list2.append(abs(a-(b+1))+abs(a-c)+abs((b+1)-c))
list2.append(abs(a-(b-1))+abs(a-c)+abs((b-1)-c))
list2.append(abs(a-(b))+abs(a-(c+1))+abs((b)-(c+1)))
list2.append(abs(a-(b))+abs(a-(c-1))+abs((b)-(c-1)))
list2.append(abs((a+1)-b)+abs((a+1)-c)+abs(b-c))
list2.append(abs((a+1)-(b+1))+abs((a+1)-c)+abs((b+1)-c))
list2.append(abs((a+1)-(b-1))+abs((a+1)-c)+abs((b-1)-c))
list2.append(abs((a+1)-(b))+abs((a+1)-(c+1))+abs((b)-(c+1)))
list2.append(abs((a+1)-(b+1))+abs((a+1)-(c+1))+abs((b+1)-(c+1)))
list2.append(abs((a+1)-(b+1))+abs((a+1)-(c-1))+abs((b+1)-(c-1)))
list2.append(abs((a+1)-(b))+abs((a+1)-(c-1))+abs((b)-(c-1)))
list2.append(abs((a-1)-b)+abs((a-1)-c)+abs(b-c))
list2.append(abs((a-1)-(b+1))+abs((a-1)-c)+abs((b+1)-c))
list2.append(abs((a-1)-(b-1))+abs((a-1)-c)+abs((b-1)-c))
list2.append(abs((a-1)-(b))+abs((a-1)-(c-1))+abs((b)-(c-1)))
list2.append(abs((a-1)-(b))+abs((a-1)-(c-1))+abs((b)-(c-1)))
#print(list2)
print(min(list2))
n=n-1
``` | instruction | 0 | 73,438 | 3 | 146,876 |
No | output | 1 | 73,438 | 3 | 146,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of test cases.
The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≤ a, b, c ≤ 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.
Output
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
Example
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
Submitted Solution:
```
n = int(input())
for _ in range(n):
l = list(map(int, input().split()))
l.sort()
print(l)
a = l[0]
b = l[1]
c = l[2]
if(a == b == c):
print(0)
elif(a != b != c):
if(a + 1 == b == c - 1):
print(0)
else:
a += 1
c -= 1
print(abs(a - b) + abs(a - c) + abs(b - c))
elif(a == b != c):
c -= 1
print(abs(a - b) + abs(a - c) + abs(b - c))
else:
a += 1
b -= 1
c -= 1
print(abs(a - b) + abs(a - c) + abs(b - c))
``` | instruction | 0 | 73,439 | 3 | 146,878 |
No | output | 1 | 73,439 | 3 | 146,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of test cases.
The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≤ a, b, c ≤ 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.
Output
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
Example
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
Submitted Solution:
```
# from debug import debug
t = int(input())
for _ in range(t):
lis = list(map(int, input().split()))
a,b,c = sorted(lis)
if a == b == c:
print(0)
elif a == b:
print(2*abs(c-b-1))
elif b == c:
print(2*abs(b-a-1))
else:
print(abs(c-b-1)+abs(b-a-1)+abs(c-a-2))
``` | instruction | 0 | 73,440 | 3 | 146,880 |
No | output | 1 | 73,440 | 3 | 146,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (i.e. set x := x - 1 or x := x + 1) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a', b' and c' be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is |a' - b'| + |a' - c'| + |b' - c'|, where |x| is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 1000) — the number of test cases.
The next q lines describe test cases. The i-th test case is given as three integers a, b and c (1 ≤ a, b, c ≤ 10^9) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.
Output
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
Example
Input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
Output
0
36
0
0
1999999994
1999999994
2
4
Submitted Solution:
```
def differance(f1,f2,f3):
return (abs(f1-f2)+abs(f2-f3)+ abs(f1-f3))
repeat = int(input())
for rep in range(repeat):
a=list(map(int , input().split()))
f3=max(a)
a.remove(f3)
f1=min(a)
a.remove(f1)
f2= 0
for i in a:
f2 = i
#real implimentation starts
if(f1!=f2):
f1+=1
if(f3!=f2):
f3-=1
print(differance(f1,f2,f3))
``` | instruction | 0 | 73,441 | 3 | 146,882 |
No | output | 1 | 73,441 | 3 | 146,883 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is dark times in Berland. Berlyand opposition, funded from a neighboring state, has organized a demonstration in Berland capital Bertown. Through the work of intelligence we know that the demonstrations are planned to last for k days.
Fortunately, Berland has a special police unit, which can save the country. It has exactly n soldiers numbered from 1 to n. Berland general, the commander of the detachment, must schedule the detachment's work in these difficult k days. In each of these days, the general must send a certain number of police officers to disperse riots. Since the detachment is large and the general is not very smart, he can only select a set of all soldiers numbered from l to r, inclusive, where l and r are selected arbitrarily.
Now the general has exactly two problems. First, he cannot send the same group twice — then soldiers get bored and they rebel. Second, not all soldiers are equally reliable. Every soldier has a reliability of ai. The reliability of the detachment is counted as the sum of reliabilities of soldiers in it. The reliability of a single soldier can be negative, then when you include him in the detachment, he will only spoil things. The general is distinguished by his great greed and shortsightedness, so each day he sends to the dissolution the most reliable group of soldiers possible (that is, of all the groups that have not been sent yet).
The Berland Government has decided to know what would be the minimum reliability of the detachment, sent to disperse the demonstrations during these k days. The general himself can not cope with such a difficult task. Help him to not embarrass himself in front of his superiors!
Input
The first line contains two integers n and k <image> — the number of soldiers in the detachment and the number of times somebody goes on duty.
The second line contains n space-separated integers ai, their absolute value doesn't exceed 109 — the soldiers' reliabilities.
Please do not use the %lld specifier to read or write 64-bit integers in С++, it is preferred to use cin, cout streams of the %I64d specifier.
Output
Print a single number — the sought minimum reliability of the groups that go on duty during these k days.
Examples
Input
3 4
1 4 2
Output
4
Input
4 6
2 -1 2 -1
Output
1
Input
8 10
1 -2 3 -4 5 -6 7 -8
Output
2
Submitted Solution:
```
n,k = list(map(int, input().split(" ")))
arr = list(map(int, input().split(" ")))
res = arr[:]
for i in range(n):
sub = arr[i]
for j in range(i+1, n):
sub = sub + arr[j]
res.append(sub)
def partitions(arr, start , end):
if start >= end:
return -1
flag = arr[start]
left = start
right = end
while left < right:
while right > left and arr[right] <= flag:
right = right -1
if right > left:
arr[left] = arr[right]
while left < right and arr[left] >= flag:
left = left + 1
if left < right:
arr[right] = arr[left]
#right = right - 1
arr[left] = flag
return left
def findKth(arr, start , end, k):
left = partitions(arr, start , end)
if left == k - 1:
return left
if left > k -1:
return partitions(arr, start, left - 1)
elif left < k:
return partitions(arr, left + 1, end)
print(arr[findKth(res, 0, len(res)-1, k)])
#print(res)
``` | instruction | 0 | 73,606 | 3 | 147,212 |
No | output | 1 | 73,606 | 3 | 147,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is dark times in Berland. Berlyand opposition, funded from a neighboring state, has organized a demonstration in Berland capital Bertown. Through the work of intelligence we know that the demonstrations are planned to last for k days.
Fortunately, Berland has a special police unit, which can save the country. It has exactly n soldiers numbered from 1 to n. Berland general, the commander of the detachment, must schedule the detachment's work in these difficult k days. In each of these days, the general must send a certain number of police officers to disperse riots. Since the detachment is large and the general is not very smart, he can only select a set of all soldiers numbered from l to r, inclusive, where l and r are selected arbitrarily.
Now the general has exactly two problems. First, he cannot send the same group twice — then soldiers get bored and they rebel. Second, not all soldiers are equally reliable. Every soldier has a reliability of ai. The reliability of the detachment is counted as the sum of reliabilities of soldiers in it. The reliability of a single soldier can be negative, then when you include him in the detachment, he will only spoil things. The general is distinguished by his great greed and shortsightedness, so each day he sends to the dissolution the most reliable group of soldiers possible (that is, of all the groups that have not been sent yet).
The Berland Government has decided to know what would be the minimum reliability of the detachment, sent to disperse the demonstrations during these k days. The general himself can not cope with such a difficult task. Help him to not embarrass himself in front of his superiors!
Input
The first line contains two integers n and k <image> — the number of soldiers in the detachment and the number of times somebody goes on duty.
The second line contains n space-separated integers ai, their absolute value doesn't exceed 109 — the soldiers' reliabilities.
Please do not use the %lld specifier to read or write 64-bit integers in С++, it is preferred to use cin, cout streams of the %I64d specifier.
Output
Print a single number — the sought minimum reliability of the groups that go on duty during these k days.
Examples
Input
3 4
1 4 2
Output
4
Input
4 6
2 -1 2 -1
Output
1
Input
8 10
1 -2 3 -4 5 -6 7 -8
Output
2
Submitted Solution:
```
n,k = list(map(int, input().split(" ")))
arr = list(map(int, input().split(" ")))
res = arr[:]
for i in range(n):
sub = arr[i]
for j in range(i+1, n):
sub = sub + arr[j]
res.append(sub)
def qsort(arr, start , end, k):
if start >= end:
return
flag = arr[start]
left = start
right = end
while left < right:
while right > left and arr[right] <= flag:
right = right -1
if right > left:
arr[left] = arr[right]
while left < right and arr[left] >= flag:
left = left + 1
if left < right:
arr[right] = arr[left]
#right = right - 1
arr[left] = flag
if left == k-1:
print(arr[left])
return arr[left]
qsort(arr, start, left - 1, k)
qsort(arr, left + 1, end, k)
qsort(res, 0, len(res)-1, k)
#print(res)
``` | instruction | 0 | 73,607 | 3 | 147,214 |
No | output | 1 | 73,607 | 3 | 147,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.
In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.
Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
Input
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn.
* 1 ≤ n ≤ 5000
* 1 ≤ x ≤ 109
* 1 ≤ lstart ≤ lend ≤ 109
Output
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
Examples
Input
5 4
2 7
9 16
8 10
9 17
1 6
Output
8
Note
Before 1. turn move to position 5
Before 2. turn move to position 9
Before 5. turn move to position 8
Submitted Solution:
```
import sys
a = input()
n , l = a.split(' ')
n = int(n)
l= int(l)
r = l
ans = 0
for i in range(1,n+1):
b=input()
l1,r1 = b.split(' ')
l1=int(l1)
r1=int(r1)
if(l1<=l and r<=r1):
continue
if(r1<l):
ans+=l-r1
r=l
l=r1
if(r<l1):
ans+=l1-r
l=r
r=l1
else:
l=max(l1,l)
r=max(r1,r)
print(ans)
``` | instruction | 0 | 73,738 | 3 | 147,476 |
No | output | 1 | 73,738 | 3 | 147,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.
In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.
Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
Input
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn.
* 1 ≤ n ≤ 5000
* 1 ≤ x ≤ 109
* 1 ≤ lstart ≤ lend ≤ 109
Output
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
Examples
Input
5 4
2 7
9 16
8 10
9 17
1 6
Output
8
Note
Before 1. turn move to position 5
Before 2. turn move to position 9
Before 5. turn move to position 8
Submitted Solution:
```
n, x = map(int, input().split())
cost = 0
for l, r in (map(int, input().split()) for _ in range(n)):
if l <= x <= r:
continue
if x < l:
cost += l-x
x = l
if x > r:
cost += x-r
x = r
print(cost)
``` | instruction | 0 | 73,740 | 3 | 147,480 |
No | output | 1 | 73,740 | 3 | 147,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.
In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.
Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.
Input
The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn.
* 1 ≤ n ≤ 5000
* 1 ≤ x ≤ 109
* 1 ≤ lstart ≤ lend ≤ 109
Output
Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.
Examples
Input
5 4
2 7
9 16
8 10
9 17
1 6
Output
8
Note
Before 1. turn move to position 5
Before 2. turn move to position 9
Before 5. turn move to position 8
Submitted Solution:
```
n, x = map(int, input().split())
lr = [tuple(map(int, input().split())) for _ in range(n)]
best = 987654321
Q = [(0, 0, x)]
while Q:
cost, now, x = Q.pop()
if now == n:
best = min(best, cost)
continue
if cost > best:
continue
l, r = lr[now]
if l <= x <= r:
dc = 0
if x < l:
dc = l-x
if x > r:
dc = x-r
Q.append((cost+dc, now+1, x))
if x < l:
dc = l-x
x = l
if x > r:
dc = x-r
x = r
Q.append((cost+dc, now+1, x))
print(best)
``` | instruction | 0 | 73,741 | 3 | 147,482 |
No | output | 1 | 73,741 | 3 | 147,483 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds. | instruction | 0 | 73,761 | 3 | 147,522 |
Tags: geometry, math
Correct Solution:
```
#!/usr/bin/env python3
# 667A_rain.py - Codeforces.com/problemset/problem/667/A by Sergey 2016
import unittest
import sys
###############################################################################
# Rain Class (Main Program)
###############################################################################
class Rain:
""" Rain representation """
def __init__(self, test_inputs=None):
""" Default constructor """
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
# Reading single elements
[self.d, self.h, self.v, self.e] = map(int, uinput().split())
def calculate(self):
""" Main calcualtion function of the class """
result = "NO"
pi = 3.141592653589793238462
vv = float(self.v) * 4 / (pi * self.d * self.d)
if vv > self.e:
result = "YES\n"
result += str(float(self.h) / (vv - self.e))
return str(result)
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_single_test(self):
""" Rain class testing """
# Constructor test
test = "1 2 3 10"
d = Rain(test)
self.assertEqual(d.d, 1)
# Sample test
self.assertEqual(Rain(test).calculate(), "NO")
# Sample test
test = "1 1 1 1"
self.assertEqual(Rain(test).calculate(), "YES\n3.6597923663254868")
# Sample test
test = ""
# self.assertEqual(Rain(test).calculate(), "0")
# My tests
test = ""
# self.assertEqual(Rain(test).calculate(), "0")
# Time limit test
# self.time_limit_test(5000)
def time_limit_test(self, nmax):
""" Timelimit testing """
import random
import timeit
# Random inputs
test = str(nmax) + " " + str(nmax) + "\n"
numnums = [str(i) + " " + str(i+1) for i in range(nmax)]
test += "\n".join(numnums) + "\n"
nums = [random.randint(1, 10000) for i in range(nmax)]
test += " ".join(map(str, nums)) + "\n"
# Run the test
start = timeit.default_timer()
d = Rain(test)
calc = timeit.default_timer()
d.calculate()
stop = timeit.default_timer()
print("\nTimelimit Test: " +
"{0:.3f}s (init {1:.3f}s calc {2:.3f}s)".
format(stop-start, calc-start, stop-calc))
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(Rain().calculate())
``` | output | 1 | 73,761 | 3 | 147,523 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds. | instruction | 0 | 73,762 | 3 | 147,524 |
Tags: geometry, math
Correct Solution:
```
import math
d,h,v,e=map(int,input().split())
H=v/(math.pi*((d/2)**2))
if H-e<0:
print("NO")
else:
print("YES")
print((h/(H-e)))
``` | output | 1 | 73,762 | 3 | 147,525 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds. | instruction | 0 | 73,763 | 3 | 147,526 |
Tags: geometry, math
Correct Solution:
```
import math
d, h, v, e = map(int, input().split())
S = math.pi * (d ** 2) / 4
q = v / S
if e > q:
print('NO')
else:
print('YES', h / (q - e), sep='\n')
``` | output | 1 | 73,763 | 3 | 147,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds. | instruction | 0 | 73,764 | 3 | 147,528 |
Tags: geometry, math
Correct Solution:
```
import math
d, h, v, e = [int(i) for i in input().split()]
t = e*d**2*math.pi/4
if t >= v:
print("NO")
else:
print("YES")
print(d**2*math.pi/4*h/(v-t))
``` | output | 1 | 73,764 | 3 | 147,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds. | instruction | 0 | 73,765 | 3 | 147,530 |
Tags: geometry, math
Correct Solution:
```
from math import pi
d1=input().split()
d1=[int(x) for x in d1]
d=d1[0]
h=d1[1]
v=d1[2]/(pi*(d/2)**2)
e=d1[3]
V=pi*(d/2)**2*h
if e>=v:
print("NO")
else:
print("YES")
print(V/((v-e)*pi*(d/2)**2))
``` | output | 1 | 73,765 | 3 | 147,531 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds. | instruction | 0 | 73,766 | 3 | 147,532 |
Tags: geometry, math
Correct Solution:
```
#!/usr/bin/env python
import os
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from io import BytesIO, IOBase
from itertools import (
accumulate, combinations, combinations_with_replacement, groupby,
permutations, product)
from math import (
acos, asin, atan, ceil, cos, degrees, factorial, hypot, log2, pi, radians,
sin, sqrt, tan)
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits
def inp():
return(int(input()))
def inlist():
return(list(map(int, input().split())))
def instr():
s = input()
return(list(s[:len(s)]))
def invr():
return(map(int, input().split()))
def main():
# # For getting input from input.txt file
# sys.stdin = open('input.txt', 'r')
# # Printing the Output to output.txt file
# sys.stdout = open('output.txt', 'w')
d, h, v, e = invr()
r = d / 2
dec = v / (pi * r**2)
if e > dec:
print("NO")
else:
print("YES")
speed = dec - e
print(h / speed)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | output | 1 | 73,766 | 3 | 147,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds. | instruction | 0 | 73,767 | 3 | 147,534 |
Tags: geometry, math
Correct Solution:
```
#!/usr/bin/env python3
from math import pi
def main():
dia, initial, speed, growth = (int(x) for x in input().split())
vol = (dia/2)**2*initial*pi
if (dia/2)**2*pi*growth >= speed:
print("NO")
quit()
print("YES")
print(vol/((speed - (dia/2)**2*pi*growth)))
if __name__=="__main__":
main()
``` | output | 1 | 73,767 | 3 | 147,535 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds. | instruction | 0 | 73,768 | 3 | 147,536 |
Tags: geometry, math
Correct Solution:
```
from math import pi
d,h,v,e = list(map(int, input().split()))
a = (d**2 / 4)*pi*h
ve = (d**2 / 4)*pi*e
if (v > ve):
print("YES")
print(a / (v - ve))
else:
print("NO")
``` | output | 1 | 73,768 | 3 | 147,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
Submitted Solution:
```
from math import pi
d, h, v, e = map(int, input().split())
r = d / 2
volume = pi * r ** 2 * h
cnt = 0
fill = e * pi * r ** 2
if v < fill:
print("NO")
exit()
print("YES")
volume = pi * r ** 2 * h
up = fill - v
print(abs(volume / up))
``` | instruction | 0 | 73,769 | 3 | 147,538 |
Yes | output | 1 | 73,769 | 3 | 147,539 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
Submitted Solution:
```
import math
d, h, v, e = map(int, input().split())
decrease_per_second = v / (math.pi * ((d / 2) ** 2))
decrease = decrease_per_second - e
if decrease <= 0:
print('NO')
else:
decrease_vol = math.pi * ((d / 2) ** 2) * decrease
initial_vol = math.pi * ((d / 2) ** 2) * h
print('YES')
print(initial_vol / decrease_vol)
``` | instruction | 0 | 73,770 | 3 | 147,540 |
Yes | output | 1 | 73,770 | 3 | 147,541 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
Submitted Solution:
```
from math import *
d, h, v, e = map(int, input().split())
r = d / 2;
total = pi * r**2 * h
s = pi * r**2 * e
if s >= v :
print("NO")
else :
print("YES")
speed = v - s
print(total / speed)
``` | instruction | 0 | 73,771 | 3 | 147,542 |
Yes | output | 1 | 73,771 | 3 | 147,543 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
Submitted Solution:
```
from math import pi
def solve():
d, h, v, e = map(int, input().split())
r = d / 2
s = r * r * pi
decr = v / s
if decr <= e:
print('NO')
else:
print('YES')
print(h / (decr - e))
if __name__ == '__main__':
solve()
``` | instruction | 0 | 73,772 | 3 | 147,544 |
Yes | output | 1 | 73,772 | 3 | 147,545 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
Submitted Solution:
```
from math import pi
d,h,v,e=map(int,input().split())
r=d/2
if e>v:
print('NO')
else:
print(round(pi/(v/r**2-pi),12))
``` | instruction | 0 | 73,773 | 3 | 147,546 |
No | output | 1 | 73,773 | 3 | 147,547 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
Submitted Solution:
```
d,h,v,e=map(int,input().split())
#vol=(3.141)*(d*d)*h
inc=v/((3.141)*((d*d)/4))
#print(inc)
if inc-e<=0:
print("NO")
else:
print("YES")
print(h/(inc-e))
``` | instruction | 0 | 73,774 | 3 | 147,548 |
No | output | 1 | 73,774 | 3 | 147,549 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
Submitted Solution:
```
from math import pi
d,h,v,e=map(int,input().split())
r=d/2
if pi*r**2*e>v:
print('NO')
else:
print('YES')
base=(pi*r**2*h)
base2=(pi*r**2-v)
print(abs(base/base2))
``` | instruction | 0 | 73,775 | 3 | 147,550 |
No | output | 1 | 73,775 | 3 | 147,551 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.
<image>
You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.
Note one milliliter equals to one cubic centimeter.
Input
The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:
* d — the diameter of your cylindrical cup,
* h — the initial level of water in the cup,
* v — the speed of drinking process from the cup in milliliters per second,
* e — the growth of water because of rain if you do not drink from the cup.
Output
If it is impossible to make the cup empty, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.
Examples
Input
1 2 3 100
Output
NO
Input
1 1 1 1
Output
YES
3.659792366325
Note
In the first example the water fills the cup faster than you can drink from it.
In the second example area of the cup's bottom equals to <image>, thus we can conclude that you decrease the level of water by <image> centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in <image> seconds.
Submitted Solution:
```
import math
tab=[float(i) for i in input().split()]
d=tab[0]
h=tab[1]
v=tab[2]
e=tab[3]
he=4*v/(math.pi*d**2)
if v<=he :
print("NO")
else :
t=h/(he-v)
print("YES")
print(t)
``` | instruction | 0 | 73,776 | 3 | 147,552 |
No | output | 1 | 73,776 | 3 | 147,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of corners of the cell that are inside or on the border of the lair.
Given this information, Heidi wants to know the exact shape of the lair to rain destruction on the zombies. Help her!
<image>
Input
The input contains multiple test cases.
The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 500). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.
Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).
The last line of the file contains a zero. This line should not be treated as a test case. The sum of the N values for all tests in one file will not exceed 5000.
Output
For each test case, give the following output:
The first line of the output should contain one integer V, the number of vertices of the polygon that is the secret lair. The next V lines each should contain two integers, denoting the vertices of the polygon in the clockwise order, starting from the lexicographically smallest vertex.
Examples
Input
8
00000000
00000110
00012210
01234200
02444200
01223200
00001100
00000000
5
00000
01210
02420
01210
00000
7
0000000
0122100
0134200
0013200
0002200
0001100
0000000
0
Output
4
2 3
2 4
6 6
5 2
4
2 2
2 3
3 3
3 2
3
2 5
4 5
4 2
Note
It is guaranteed that the solution always exists and is unique. It is guaranteed that in the correct solution the coordinates of the polygon vertices are between 2 and N - 2. A vertex (x1, y1) is lexicographically smaller than vertex (x2, y2) if x1 < x2 or <image>.
Submitted Solution:
```
def main():
while True:
size = int(input())
if size == 0:
break
sq = [list(map(int, input().strip())) for _ in range(size)]
printpts(corners(sq))
def corners(sq):
sq.reverse()
for i, row in enumerate(sq):
if not all(elt == 0 for elt in row):
break
ones = [col for col, c in enumerate(row) if c == 1]
left = [(ones[0]+1, i+1)]
right = [(ones[-1], i+1)]
for j in range(i+1, len(sq)):
currow = sq[j]
if not any(currow):
break
ones = [col for col, c in enumerate(currow) if c == 1]
for one in ones:
corner = findcorner(sq, one, j)
isleft = sq[j][one-1] == 0
addcorner(left if isleft else right, corner, isleft)
if left[0] == right[0]:
left = left[1:]
if left[-1] == right[-1]:
left.pop()
left.extend(reversed(right))
return left
def findcorner(sq, x, y):
xans, yans = x, y
if sq[y][x-1] == 0:
xans += 1
if sq[y-1][x] == 0:
yans += 1
return xans, yans
def addcorner(lst, corner, turnright):
if corner == lst[-1]:
return
if len(lst) > 1:
(x0, y0), (x1, y1) = lst[-2:]
dx, dy = x1-x0, y1-y0
cross = dy * (corner[0] - x0) - dx * (corner[1] - y0)
override = cross <= 0 if turnright else cross >= 0
if override:
lst[-1] = corner
return
lst.append(corner)
def printpts(lst):
print(len(lst))
start = lst.index(min(lst))
for x, y in lst[start:] + lst[:start]:
print(x, y)
main()
``` | instruction | 0 | 73,778 | 3 | 147,556 |
No | output | 1 | 73,778 | 3 | 147,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of corners of the cell that are inside or on the border of the lair.
Given this information, Heidi wants to know the exact shape of the lair to rain destruction on the zombies. Help her!
<image>
Input
The input contains multiple test cases.
The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 500). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.
Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).
The last line of the file contains a zero. This line should not be treated as a test case. The sum of the N values for all tests in one file will not exceed 5000.
Output
For each test case, give the following output:
The first line of the output should contain one integer V, the number of vertices of the polygon that is the secret lair. The next V lines each should contain two integers, denoting the vertices of the polygon in the clockwise order, starting from the lexicographically smallest vertex.
Examples
Input
8
00000000
00000110
00012210
01234200
02444200
01223200
00001100
00000000
5
00000
01210
02420
01210
00000
7
0000000
0122100
0134200
0013200
0002200
0001100
0000000
0
Output
4
2 3
2 4
6 6
5 2
4
2 2
2 3
3 3
3 2
3
2 5
4 5
4 2
Note
It is guaranteed that the solution always exists and is unique. It is guaranteed that in the correct solution the coordinates of the polygon vertices are between 2 and N - 2. A vertex (x1, y1) is lexicographically smaller than vertex (x2, y2) if x1 < x2 or <image>.
Submitted Solution:
```
def main():
while True:
size = int(input())
if size == 0:
break
sq = [list(map(int, input().strip())) for _ in range(size)]
printpts(corners(sq))
def corners(sq):
sq.reverse()
for i, row in enumerate(sq):
if not all(elt == 0 for elt in row):
break
ones = [col for col, c in enumerate(row) if c == 1]
left = [(ones[0]+1, i+1)]
right = [(ones[-1], i+1)]
for j in range(i+1, len(sq)):
currow = sq[j]
if not any(currow):
break
ones = [col for col, c in enumerate(currow) if c == 1]
for one in ones:
corner = findcorner(sq, one, j)
addcorner(left if sq[j][one-1] == 0 else right, corner)
if left[0] == right[0]:
left = left[1:]
if left[-1] == right[-1]:
left.pop()
left.extend(reversed(right))
return left
def findcorner(sq, x, y):
xans, yans = x, y
if sq[y][x-1] == 0:
xans += 1
if sq[y-1][x] == 0:
yans += 1
return xans, yans
def addcorner(lst, corner):
if corner == lst[-1]:
return
if len(lst) > 1:
(x0, y0), (x1, y1) = lst[-2:]
dx, dy = x1-x0, y1-y0
if dy * (corner[0] - x0) <= dx * (corner[1] - y0):
lst[-1] = corner
return
lst.append(corner)
def printpts(lst):
print(len(lst))
start = lst.index(min(lst))
for x, y in lst[start:] + lst[:start]:
print(x, y)
main()
``` | instruction | 0 | 73,779 | 3 | 147,558 |
No | output | 1 | 73,779 | 3 | 147,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image>
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
n,k = Ri()
lis = [i for i in range(k)]
ans = []
cur = k
totans = 0
while True:
tlis = []
while len(lis):
if cur == n-1: break
# temp =
ans.append((lis[-1], cur))
tlis.append(cur)
cur+=1
lis.pop()
if len(lis) != 0:
for i in tlis:
ans.append((i, cur))
for i in lis:
ans.append((i, cur))
if len(tlis) == 1:
totans+=2
totans = totans+(totans-1)
elif len(tlis) >= 2:
totans+=2
totans = totans*2
else:
# print(totans)
totans+=1
totans = 2*totans
break
lis = tlis
totans+=1
print(totans)
for i in ans:
print(i[0]+1, i[1]+1)
``` | instruction | 0 | 73,853 | 3 | 147,706 |
Yes | output | 1 | 73,853 | 3 | 147,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image>
Submitted Solution:
```
from sys import stdin, stdout
n,k = map(int,stdin.readline().rstrip().split())
print(2+(n-2)//k+(n-3)//k)
connectionsList = []
# Leaf node is 1. Make this node have connections to k children
for i in range(k):
connectionsList.append((str(1),str(i+2)))
for i in range(k+2,n+1):
connectionsList.append((str(i-k),str(i)))
for conn in connectionsList:
print(' '.join(conn))
``` | instruction | 0 | 73,854 | 3 | 147,708 |
Yes | output | 1 | 73,854 | 3 | 147,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image>
Submitted Solution:
```
n, k = map(int, input().split())
mid = n-k-1
r = [0] * k
for i in range(n-1):
r[i%k] += 1
print(r[0]+r[1])
v1 = 2
ans = []
for i in range(k):
v0 = 1
for _ in range(r[i]):
ans.append("%d %d"%(v0, v1))
v0 = v1
v1 += 1
print("\n".join(ans))
# Made By Mostafa_Khaled
``` | instruction | 0 | 73,855 | 3 | 147,710 |
Yes | output | 1 | 73,855 | 3 | 147,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image>
Submitted Solution:
```
# -*- coding: utf-8 -*-
n, m = map(int, input().split())
a = int((n - 1) % m)
b = int((n - 1) / m)
if a == 0:
print(int(b*2))
elif a == 1:
print(int(b*2+1))
else:
print(int(b*2+2))
s = 1
now = 2
for i in range(0, m):
print('%d %d' % (s, now))
now += 1
for j in range(0, b - 1):
print('%d %d' % (now - 1, now))
now += 1
if i < a:
print('%d %d' % (now - 1, now))
now += 1
``` | instruction | 0 | 73,856 | 3 | 147,712 |
Yes | output | 1 | 73,856 | 3 | 147,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image>
Submitted Solution:
```
n,k = map(int,input().split())
k -= 2
n-=k
sp = False
val = 0
if n%2!=0 and k%2==0:
sp = True
val = (n-k+1)//2 + 1
elif n%2==0 and k%2!=0:
val = (n-k+1)//2 + 1
else:
val = (n-k)//2+1
print(val)
j = 1
for i in range(n-1):
print(j,j+1)
j+=1
if sp:
for i in range(val,val+k-1):
if i==n//2+1:
print(i,j+1)
j+=1
print(i,j+1)
else:
print(i,j+1)
j+=1
else:
for i in range(val,val+k):
print(i,j+1)
``` | instruction | 0 | 73,857 | 3 | 147,714 |
No | output | 1 | 73,857 | 3 | 147,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image>
Submitted Solution:
```
n, k = map(int, input().split())
if k == n - 1:
print(2)
for i in range(n):
if i != 1:
print(2, i + 1)
else:
if n - 1 - k > 1:
print(n - k - 1 + 2)
print(1, 2)
for i in range(k - 1):
print(3, i + 4)
rest = n - k - 2
if rest > 0:
print(2, 6)
print(n, 3)
for i in range(rest - 2):
print(i + 6, i + 7)
else:
print(n - k - 1 + 2)
print(1, 2)
print(2, 3)
for i in range(k - 1):
print(3, i + 4)
rest = n - k - 2
if rest > 0:
print(2, 6)
print(n, 3)
for i in range(rest - 2):
print(i + 6, i + 7)
``` | instruction | 0 | 73,858 | 3 | 147,716 |
No | output | 1 | 73,858 | 3 | 147,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image>
Submitted Solution:
```
n, k = map(int, input().split())
print(n - k + 1)
for i in range(n - k):
print(i + 1, i + 2)
for i in range(k - 1):
print(n - k + 1, i + n - k + 2)
``` | instruction | 0 | 73,859 | 3 | 147,718 |
No | output | 1 | 73,859 | 3 | 147,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.
Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.
Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.
Input
The first line contains two integers n and k (3 ≤ n ≤ 2·105, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.
Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.
Output
In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.
If there are multiple answers, print any of them.
Examples
Input
3 2
Output
2
1 2
2 3
Input
5 3
Output
3
1 2
2 3
3 4
3 5
Note
In the first example the only network is shown on the left picture.
In the second example one of optimal networks is shown on the right picture.
Exit-nodes are highlighted.
<image>
Submitted Solution:
```
n, k = map(int, input().split())
r = (n-1)//k
l = n - 1
x, y, = 1, 2
print(2*r + ((n-1)%k != 0))
for i in range(k):
br = r
if i < (n-1)%k:
br += 1
x = 1
for j in range(br):
print(x, y)
x = y
y = y + 1
l -= 1
``` | instruction | 0 | 73,860 | 3 | 147,720 |
No | output | 1 | 73,860 | 3 | 147,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.
Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2).
<image>
Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.
Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.
Input
The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have.
The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different.
Output
Print the minimal number of elements to be purchased.
Examples
Input
2 2 3
1 2
2 2
2 1
Output
0
Input
1 5 3
1 3
1 1
1 5
Output
2
Input
4 3 6
1 2
1 3
2 2
2 3
3 1
3 3
Output
1
Note
For each example you have a picture which illustrates it.
The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.
The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.
Test 1
We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything.
<image>
Test 2
We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.
<image>
Test 3
There are several possible solutions. One of them is illustrated below.
Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.
<image> | instruction | 0 | 74,177 | 3 | 148,354 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, matrices
Correct Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [-1]*n
self.rank = [0]*n
def Find(self, x):
if self.par[x] < 0:
return x
else:
self.par[x] = self.Find(self.par[x])
return self.par[x]
def Unite(self, x, y):
x = self.Find(x)
y = self.Find(y)
if x != y:
if self.rank[x] < self.rank[y]:
self.par[y] += self.par[x]
self.par[x] = y
else:
self.par[x] += self.par[y]
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def Same(self, x, y):
return self.Find(x) == self.Find(y)
def Size(self, x):
return -self.par[self.Find(x)]
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m, q = map(int, input().split())
uf = UnionFind(n+m)
for i in range(q):
r, c = map(int, input().split())
r, c = r-1, c-1
uf.Unite(r, c+n)
S = set()
for i in range(n+m):
S.add(uf.Find(i))
print(len(S)-1)
``` | output | 1 | 74,177 | 3 | 148,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.
Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2).
<image>
Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.
Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.
Input
The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have.
The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different.
Output
Print the minimal number of elements to be purchased.
Examples
Input
2 2 3
1 2
2 2
2 1
Output
0
Input
1 5 3
1 3
1 1
1 5
Output
2
Input
4 3 6
1 2
1 3
2 2
2 3
3 1
3 3
Output
1
Note
For each example you have a picture which illustrates it.
The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.
The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.
Test 1
We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything.
<image>
Test 2
We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.
<image>
Test 3
There are several possible solutions. One of them is illustrated below.
Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.
<image> | instruction | 0 | 74,178 | 3 | 148,356 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, matrices
Correct Solution:
```
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
"""{ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す"""
groups = {r: [] for r in self.roots()}
for i in range(self.N):
groups[self.find(i)].append(i)
return groups
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,m,q=map(int,input().split())
uf=UnionFind(n+m)
for _ in range(q):
a,b=map(int,input().split())
uf.union(a-1,b-1+n)
print(uf.group_count()-1)
``` | output | 1 | 74,178 | 3 | 148,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.
Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2).
<image>
Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.
Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.
Input
The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have.
The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different.
Output
Print the minimal number of elements to be purchased.
Examples
Input
2 2 3
1 2
2 2
2 1
Output
0
Input
1 5 3
1 3
1 1
1 5
Output
2
Input
4 3 6
1 2
1 3
2 2
2 3
3 1
3 3
Output
1
Note
For each example you have a picture which illustrates it.
The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.
The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.
Test 1
We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything.
<image>
Test 2
We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.
<image>
Test 3
There are several possible solutions. One of them is illustrated below.
Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.
<image> | instruction | 0 | 74,179 | 3 | 148,358 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, matrices
Correct Solution:
```
from sys import stdin
class DSU:
def __init__(self, n) -> None:
self.parent = [i for i in range(n)]
self.rank =[0]*n
def find_set(self, v):
w = v
parent = self.parent
while parent[v] != v:
v = parent[v]
while parent[w] != w:
t = parent[w]
parent[w] = v
w = t
return v
def union_sets(self, a, b):
a = self.find_set(a)
b = self.find_set(b)
rank = self.rank
if a != b:
if rank[a] < rank[b]:
rank[a], rank[b] = rank[b], rank[a]
self.parent[b] = a
if rank[a] == rank[b]:
rank[a] += 1
n,m,q=map(int,stdin.readline().split())
dsu=DSU(n+m)
for i in range(q):
r,c = map(int, stdin.readline().split())
r-=1
c-=1
dsu.union_sets(r, c+n)
ans = -1
for i in range(n+m):
if dsu.parent[i] == i:
ans += 1
print(ans)
``` | output | 1 | 74,179 | 3 | 148,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.
Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2).
<image>
Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.
Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.
Input
The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have.
The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different.
Output
Print the minimal number of elements to be purchased.
Examples
Input
2 2 3
1 2
2 2
2 1
Output
0
Input
1 5 3
1 3
1 1
1 5
Output
2
Input
4 3 6
1 2
1 3
2 2
2 3
3 1
3 3
Output
1
Note
For each example you have a picture which illustrates it.
The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.
The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.
Test 1
We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything.
<image>
Test 2
We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.
<image>
Test 3
There are several possible solutions. One of them is illustrated below.
Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.
<image>
Submitted Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [-1]*n
self.rank = [0]*n
def Find(self, x):
if self.par[x] < 0:
return x
else:
self.par[x] = self.Find(self.par[x])
return self.par[x]
def Unite(self, x, y):
x = self.Find(x)
y = self.Find(y)
if x != y:
if self.rank[x] < self.rank[y]:
self.par[y] += self.par[x]
self.par[x] = y
else:
self.par[x] += self.par[y]
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def Same(self, x, y):
return self.Find(x) == self.Find(y)
def Size(self, x):
return -self.par[self.Find(x)]
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m, q = map(int, input().split())
uf = UnionFind(n+m)
for i in range(q):
r, c = map(int, input().split())
r, c = r-1, c-1
uf.Unite(r, c+n)
ans = 0
for i in range(n+m):
if uf.Size(i) == 1:
ans += 1
print(ans)
``` | instruction | 0 | 74,180 | 3 | 148,360 |
No | output | 1 | 74,180 | 3 | 148,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[Æsir - CHAOS](https://soundcloud.com/kivawu/aesir-chaos)
[Æsir - V.](https://soundcloud.com/kivawu/aesir-v)
"Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.
The time right now...... 00:01:12......
It's time."
The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.
The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1, 2, 3, …). The node with a number x (x > 1), is directly connected with a node with number (x)/(f(x)), with f(x) being the lowest prime divisor of x.
Vanessa's mind is divided into n fragments. Due to more than 500 years of coma, the fragments have been scattered: the i-th fragment is now located at the node with a number k_i! (a factorial of k_i).
To maximize the chance of successful awakening, Ivy decides to place the samples in a node P, so that the total length of paths from each fragment to P is smallest possible. If there are multiple fragments located at the same node, the path from that node to P needs to be counted multiple times.
In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.
But for a mere human like you, is this still possible?
For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node P.
Input
The first line contains an integer n (1 ≤ n ≤ 10^6) — number of fragments of Vanessa's mind.
The second line contains n integers: k_1, k_2, …, k_n (0 ≤ k_i ≤ 5000), denoting the nodes where fragments of Vanessa's mind are located: the i-th fragment is at the node with a number k_i!.
Output
Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node P).
As a reminder, if there are multiple fragments at the same node, the distance from that node to P needs to be counted multiple times as well.
Examples
Input
3
2 1 4
Output
5
Input
4
3 1 4 4
Output
6
Input
4
3 1 4 1
Output
6
Input
5
3 1 4 1 5
Output
11
Note
Considering the first 24 nodes of the system, the node network will look as follows (the nodes 1!, 2!, 3!, 4! are drawn bold):
<image>
For the first example, Ivy will place the emotion samples at the node 1. From here:
* The distance from Vanessa's first fragment to the node 1 is 1.
* The distance from Vanessa's second fragment to the node 1 is 0.
* The distance from Vanessa's third fragment to the node 1 is 4.
The total length is 5.
For the second example, the assembly node will be 6. From here:
* The distance from Vanessa's first fragment to the node 6 is 0.
* The distance from Vanessa's second fragment to the node 6 is 2.
* The distance from Vanessa's third fragment to the node 6 is 2.
* The distance from Vanessa's fourth fragment to the node 6 is again 2.
The total path length is 6.
Submitted Solution:
```
from sys import stdin, stdout
prime = list()
factor = list()
count = list()
dist = list()
N = 0
debugs = False
def find_prime():
global prime
for i in range(2, 5010):
is_prime = True
for j in prime:
if i % j == 0:
is_prime = False
break
if is_prime is True:
prime.append(i)
def calculate_factor(max):
global prime
global factor
global dist
factor = [[0 for x in range(len(prime))] for y in range(5010)]
dist = [0] * (max+1)
d = 0
for i in range(1, max+1):
temp = i
factor[i] = list(factor[i-1])
for j,x in enumerate(prime):
while temp % x == 0:
factor[i][j] +=1
temp = temp / x
d += 1
if temp == 1:
dist[i] = d
break
def dynamic_count():
global count
for i in range (1,len(count)):
count[i] += count[i-1]
def moving(i, left, right, d, current_factor):
global count
global prime
global factor
global N
while (factor[left][i] == factor[right][i]):
if (debugs is True and prime[i] <= 5):
print("deb",prime[i],left,right,count[right] - count[left-1], factor[left][i], factor[right][i])
d += ((2 * (count[right] - count[left-1])) - N) * (factor[right][i] - current_factor[i])
current_factor[i] = factor[right][i]
i -= 1
if i < 0:
return d
if (debugs is True):
print(prime[i],left,right,count[right] - count[left-1], factor[left][i], factor[right][i])
d += ((2 * (count[right] - count[left-1])) - N) * (factor[left][i] - current_factor[i])
current_factor[i] = factor[left][i]
temp_left = right
while temp_left >= left:
if (factor[temp_left-1][i] != factor[right][i] or temp_left == left ) and count[right] - count[temp_left-1] > int(N/2):
return moving(i, temp_left, right, d, current_factor)
elif factor[temp_left-1][i] != factor[right][i]:
i -= 1
right = temp_left - 1
if i < 0:
return d
temp_left -= 1
return d
def unanem():
global prime
global count
global N
if count[1] > int(N/2):
return 0
current_factor = [0] * 5010
if count[5000] - count[4998] > int(N/2):
return moving(len(prime)-3, 4999, 5000, 0, current_factor)
for i,x in enumerate(prime):
counter = 0
if i == 0:
counter = count[1]
else:
counter = count[prime[i] - 1] - count[prime[i-1] - 1]
if counter>int(N/2):
return moving (i, prime[i-1], prime[i] - 1, 0 , current_factor)
return 0
def main():
global prime
global factor
global count
global N
global debugs
N = int(stdin.readline())
num_list = list(map(int, stdin.readline().split()))
max = 0
for i in num_list:
if max < i:
max = i
if num_list[0] == 2976 and num_list[1] == 2807:
debugs = True
count = [0] * (5010)
for i in num_list:
count[i] += 1
find_prime()
calculate_factor(max)
dynamic_count()
d = unanem()
overall_dist = 0
for i,c in enumerate(count):
if i == max + 1:
break
if i == 0:
continue
overall_dist += (count[i] - count[i-1])*dist[i]
print(overall_dist - d)
main()
``` | instruction | 0 | 74,272 | 3 | 148,544 |
No | output | 1 | 74,272 | 3 | 148,545 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[Æsir - CHAOS](https://soundcloud.com/kivawu/aesir-chaos)
[Æsir - V.](https://soundcloud.com/kivawu/aesir-v)
"Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.
The time right now...... 00:01:12......
It's time."
The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.
The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1, 2, 3, …). The node with a number x (x > 1), is directly connected with a node with number (x)/(f(x)), with f(x) being the lowest prime divisor of x.
Vanessa's mind is divided into n fragments. Due to more than 500 years of coma, the fragments have been scattered: the i-th fragment is now located at the node with a number k_i! (a factorial of k_i).
To maximize the chance of successful awakening, Ivy decides to place the samples in a node P, so that the total length of paths from each fragment to P is smallest possible. If there are multiple fragments located at the same node, the path from that node to P needs to be counted multiple times.
In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.
But for a mere human like you, is this still possible?
For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node P.
Input
The first line contains an integer n (1 ≤ n ≤ 10^6) — number of fragments of Vanessa's mind.
The second line contains n integers: k_1, k_2, …, k_n (0 ≤ k_i ≤ 5000), denoting the nodes where fragments of Vanessa's mind are located: the i-th fragment is at the node with a number k_i!.
Output
Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node P).
As a reminder, if there are multiple fragments at the same node, the distance from that node to P needs to be counted multiple times as well.
Examples
Input
3
2 1 4
Output
5
Input
4
3 1 4 4
Output
6
Input
4
3 1 4 1
Output
6
Input
5
3 1 4 1 5
Output
11
Note
Considering the first 24 nodes of the system, the node network will look as follows (the nodes 1!, 2!, 3!, 4! are drawn bold):
<image>
For the first example, Ivy will place the emotion samples at the node 1. From here:
* The distance from Vanessa's first fragment to the node 1 is 1.
* The distance from Vanessa's second fragment to the node 1 is 0.
* The distance from Vanessa's third fragment to the node 1 is 4.
The total length is 5.
For the second example, the assembly node will be 6. From here:
* The distance from Vanessa's first fragment to the node 6 is 0.
* The distance from Vanessa's second fragment to the node 6 is 2.
* The distance from Vanessa's third fragment to the node 6 is 2.
* The distance from Vanessa's fourth fragment to the node 6 is again 2.
The total path length is 6.
Submitted Solution:
```
from sys import stdin, stdout
prime = list()
factor = list()
count = list()
dist = list()
N = 0
debugs = False
def find_prime():
global prime
for i in range(2, 5010):
is_prime = True
for j in prime:
if i % j == 0:
is_prime = False
break
if is_prime is True:
prime.append(i)
def calculate_factor(max):
global prime
global factor
global dist
factor = [[0 for x in range(len(prime))] for y in range(5010)]
dist = [0] * (max+1)
d = 0
for i in range(1, max+1):
temp = i
factor[i] = list(factor[i-1])
for j,x in enumerate(prime):
while temp % x == 0:
factor[i][j] +=1
temp = temp / x
d += 1
if temp == 1:
dist[i] = d
break
def dynamic_count():
global count
for i in range (1,len(count)):
count[i] += count[i-1]
def moving(i, left, right, d, current_factor):
global count
global prime
global factor
global N
while (factor[left][i] == factor[right][i]):
d += ((2 * (count[right] - count[left-1])) - N) * (factor[right][i] - current_factor[i])
if (debugs is True and current_factor[i] != 0):
print("deb",d,prime[i],left,right,count[right] - count[left-1], factor[left][i], current_factor[i])
current_factor[i] = factor[right][i]
i -= 1
if i < 0:
return d
if (debugs is True):
print(prime[i],left,right,count[right] - count[left-1], factor[left][i], factor[right][i])
d += ((2 * (count[right] - count[left-1])) - N) * (factor[left][i] - current_factor[i])
current_factor[i] = factor[left][i]
temp_left = right
while temp_left >= left:
if (factor[temp_left-1][i] != factor[right][i] or temp_left == left ) and count[right] - count[temp_left-1] > int(N/2):
if (temp_left > left):
d += ((2 * (count[temp_left-1] - count[left-1])) - N) * (factor[left][i] - current_factor[i])
return moving(i, temp_left, right, d, current_factor)
elif factor[temp_left-1][i] != factor[right][i]:
i -= 1
right = temp_left - 1
if i < 0:
return d
temp_left -= 1
return d
def unanem():
global prime
global count
global N
if count[1] > int(N/2):
return 0
current_factor = [0] * 5010
if count[5000] - count[4998] > int(N/2):
return moving(len(prime)-3, 4999, 5000, 0, current_factor)
for i,x in enumerate(prime):
counter = 0
if i == 0:
counter = count[1]
else:
counter = count[prime[i] - 1] - count[prime[i-1] - 1]
if counter>int(N/2):
return moving (i, prime[i-1], prime[i] - 1, 0 , current_factor)
return 0
def main():
global prime
global factor
global count
global N
global debugs
N = int(stdin.readline())
num_list = list(map(int, stdin.readline().split()))
max = 0
for i in num_list:
if max < i:
max = i
if num_list[0] == 2976 and num_list[1] == 2807:
debugs = True
count = [0] * (5010)
for i in num_list:
count[i] += 1
find_prime()
calculate_factor(max)
dynamic_count()
d = unanem()
overall_dist = 0
for i,c in enumerate(count):
if i == max + 1:
break
if i == 0:
continue
overall_dist += (count[i] - count[i-1])*dist[i]
print(overall_dist - d)
main()
``` | instruction | 0 | 74,273 | 3 | 148,546 |
No | output | 1 | 74,273 | 3 | 148,547 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.