text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Tags: brute force, geometry, implementation
Correct Solution:
```
x,y = map(int,input().split())
sx=sy=0
c=0
i=j=1
while(1):
p=sx
q=sy
if i%2==0:
sy=sy+((-1)**(j-1))*j
j+=1
else:
sx=sx+((-1)**(j-1))*j
if (min(p,sx)<= x and x<=max(p,sx)) and (min(q,sy)<=y and y<=max(q,sy)) and ((x==p and p==sx) or (y==q and q==sy)):
if x==p and y==q:
c=c-1
break
#print(sx,sy)
i+=1
c+=1
print(max(c,0))
```
| 4,500 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Tags: brute force, geometry, implementation
Correct Solution:
```
x, y = map(int, input().split())
if abs(y) >= abs(x) and y != 0:
if y > 0:
ans = 2*(2*y-1)
else:
ans = 4*abs(y)
if x == y:
print(ans-1)
else:
print(ans)
elif abs(x) >= abs(y) and x != 0:
if x > 0:
if x == 1:
ans = 0
else:
ans = 4*x-3
else:
ans = 4*abs(x)-1
if (x < 0 and x == -y) or(x > 0 and y == -abs(abs(x)-1)):
print(max(ans-1, 0))
else:
print(ans)
else:
print(0)
```
| 4,501 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Tags: brute force, geometry, implementation
Correct Solution:
```
def main():
x, y = map(int, input().split())
r, t = max(abs(x), abs(y)), 0
if x == r == 1 - y:
t = 4
elif x == r > -y:
t = 3
elif y == r > x:
t = 2
elif -x == r > y:
t = 1
print({(0, 0): 0, (1, 0): 0, (1, 1): 1, (0, 1): 2, (-1, 1): 2, (-1, 0): 3, (-1, -1): 3,
(0, -1): 4, (1, -1): 4}[x, y] if r < 2 else r * 4 - t)
if __name__ == '__main__':
main()
```
| 4,502 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Tags: brute force, geometry, implementation
Correct Solution:
```
'''input
37 -100
'''
p = [(0, 0)]
a, b = 0, 0
c = 1
while c < 202:
for i in range(c-1):
a += 1
p.append((a, b))
p.append((a+1, b, "*"))
a += 1
for j in range(c-1):
b += 1
p.append((a, b))
p.append((a, b+1, "*"))
b += 1
for k in range(c):
a -= 1
p.append((a, b))
p.append((a-1, b, "*"))
a -= 1
for l in range(c):
b -= 1
p.append((a, b))
p.append((a, b-1, "*"))
b -= 1
c += 2
x, y = map(int, input().split())
if (x, y) in p:
z = p.index((x, y))
elif (x, y, "*") in p:
z = p.index((x, y, "*"))
t = 0
for w in p[:z]:
if len(w) == 3:
t += 1
print(t)
```
| 4,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Tags: brute force, geometry, implementation
Correct Solution:
```
from math import floor
def main(xx, yy):
if xx == 0 and yy == 0:
return 0
if xx == 1 and yy == 0:
return 0
x = 0
y = 0
i = 0
g = [(1, 0), (0, 1), (-1, 0), (0, -1)]
while not (x == xx and y == yy):
prev_x = x
prev_y = y
x += (int(floor(i / 2) + 1) * g[i % 4][0])
y += (int(floor(i / 2) + 1) * g[i % 4][1])
i += 1
if xx >= x and xx <= prev_x and yy >= y and yy <= prev_y:
return i - 1
if xx <= x and xx >= prev_x and yy <= y and yy >= prev_y:
return i - 1
return i - 1
print(main(*list(map(int, input().split(' ')))))
```
| 4,504 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Tags: brute force, geometry, implementation
Correct Solution:
```
x, y = map(int, input().split())
a, b, cnt = 0, 0, 0
if x == y == 0: print(0); exit()
while(1):
while(a + b != 1):
a += 1
if a == x and b == y: print(cnt); exit()
cnt += 1
while(a - b != 0):
b += 1
if a == x and b == y: print(cnt); exit()
cnt += 1
while(a + b != 0):
a -= 1
if a == x and b == y: print(cnt); exit()
cnt += 1
while(a != b):
b -= 1
if a == x and b == y: print(cnt); exit()
cnt += 1
```
| 4,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Tags: brute force, geometry, implementation
Correct Solution:
```
'''l = [[(0, 0), (1, 0)],
[(1,β0),β(1,β1)],
[(1,β1),β(-1,β1)],
[(-1,β1),β(-1,β-1)],
[(-1,β-β1),β(2,β-1)],
[(2,β-1),β(2,β2)]]
'''
'''
pattern er shudhone na paria
last e net theke copy marcha
pattern copy marcha re.
'''
x,y = map(int, input().split())
if y >= x and y < -x:
print(-4*x-1)
elif y > x and y >= -x:
print(4*y-2)
elif y <= x and y > 1-x:
print(4*x-3)
elif y < x and y <= 1-x:
print(-4*y)
else:
print(0)
```
| 4,506 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Tags: brute force, geometry, implementation
Correct Solution:
```
m,n = map(int,input().split())
x = 1
y = 0
count = 0
# print(0,0)
if 0<=m<=1 and n == 0:
print(0)
else:
while True:
a1,a2 = x,y
b1,b2 = a1,abs(a2)+1
if (a1 == m and a2 < n<=b2):
count+=1
break
else:
count+=1
c1,c2 = -b1,b2
if (c1<=m<b1 and b2 == n):
count+=1
break
else:
count+=1
d1,d2 = -b1,-b2
if (d1 == m and d2 <=n< c2):
count+=1
break
else:
count+=1
x = a1+1
y = -(abs(a2)+1)
if (d1<m<=x and n == y):
count+=1
break
else:
count+=1
if (a1<=m<=b1 and b1<=n<=b2) or (c1<=m<=b1 and c2<=n<=b2) or (c1<=m<=d1 and d2<=n<=c2) or (d1<=m<=x and y<=n<=d2):
break
#
# else:
# count+=1
print(count)
```
| 4,507 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Submitted Solution:
```
x = 0
y = 0
nx,ny = map(int,input().split())
if ((nx == 0 or nx == 1) and ny == 0):
print(0)
else:
x = 1
turn = 0
flag = 0
while True:
turn = turn + 1
while y != x:
y = y + 1
if(x == nx and y == ny):
flag = 1
break
if flag == 1:
break
k = x * -1
turn = turn + 1
while x != k:
x = x - 1
if(x == nx and y == ny):
flag = 1
break
if flag == 1:
break
turn = turn + 1
while y != x:
y = y - 1
if(x == nx and y == ny):
flag = 1
break
if flag == 1:
break
k = (x * -1) + 1
turn = turn + 1
while x != k:
x = x + 1
if(x == nx and y == ny):
flag = 1
break
if flag == 1:
break
print(turn)
```
Yes
| 4,508 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Submitted Solution:
```
x, y = map(int, input().split())
if y > x >= -y:
print(y * 4 - 2)
elif y < x <= -y + 1:
print(-y * 4)
elif y <= x and x > -y + 1:
print(x * 4 - 3)
elif y >= x and x < -y:
print(-1 - 4 * x)
else:
print(0)
```
Yes
| 4,509 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Submitted Solution:
```
import time
x, y = map(int, input().split())
movements = [(1,0),(0,1),(-1,0),(0,-1)]
sizeOfSteps = 1
x_0, y_0 = 0, 0
x_1, y_1 = 1, 0
step = 0
change = 1
while not(((x_0 <= x <=x_1) or (x_0 >= x >=x_1)) and ((y_0 <= y <= y_1) or (y_0 >= y >= y_1))) :
step +=1
move_i = movements[step%4]
if change%2 == 0:
sizeOfSteps += 1
change +=1
x_0, y_0 = x_1 , y_1
x_1 = x_1 + move_i[0]*sizeOfSteps
y_1 = y_1 + move_i[1]*sizeOfSteps
"""
print("Vamos en el paso: ", step)
print(x_0,y_0)
print(x_1,y_1)
time.sleep(1)
"""
print(step)
```
Yes
| 4,510 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Submitted Solution:
```
import sys
import math
import heapq
from collections import defaultdict as dd
from itertools import permutations as pp
from itertools import combinations as cc
from sys import stdin
from functools import cmp_to_key
input=stdin.readline
m=10**9+7
sys.setrecursionlimit(10**5)
#T=int(input())
#for _ in range(T):
n,m=map(int,input().split())
x,y,c=0,0,0
if x==n and y==m:
print(c)
else:
x+=1
f1,f2,f3,f4=1,0,0,0
p,q=0,0
s=set()
s.add((1,0))
now=1
f=1
while True:
if (n,m) in s:
print(c)
break
if f1:
c+=1
y+=now
j=0
for i in range(now):
s.add((x,y+j))
j-=1
f1,f2=0,1
#print(s)
elif f2:
c+=1
now+=1
x-=now
j=0
for i in range(now):
s.add((x+j,y))
j+=1
f2,f3=0,1
elif f3:
c+=1
y-=now
j=0
for i in range(now):
s.add((x,y+j))
j+=1
f3,f4=0,1
elif f4:
c+=1
now+=1
x+=now
j=0
for i in range(now):
s.add((x+j,y))
j-=1
f4,f1=0,1
#me+=1
#print(s)
```
Yes
| 4,511 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Submitted Solution:
```
x,y=map(int,input().split())
x1=abs(x)
y1=abs(y)
mx=max(x1,y1)
if x==1 and y==0:
print(0)
elif x==0 and y==0:
print(0)
else:
if x1==y1:
if x>0:
if y>0:
print((4*x1)-3)
elif y<0:
print(4*x1)
elif x<0:
if y>0:
print((4*x1)-2)
elif y<0:
print(4*x1-1)
elif x1!=y1:
if x1==mx:
if x>0:
print((4*x1)-3)
elif x<0:
print((4*x1)-1)
elif y1==mx:
if y>0:
print((4*y1)-2)
elif y<0:
print(4*y1)
```
No
| 4,512 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Submitted Solution:
```
# one ride costs a rubes
inputs = list(map(int, input().split()))
x = inputs[0]
y = inputs[1]
if y==0 and x>0: print(0)
elif x==1:print(1)
elif y==1: print(2)
elif x==-1:print(3)
elif y==-1:print(4)
else:
a = max(abs(x), abs(y))
m = 1 + 4*(a-1)
if x==a:
if y==-(a-1): print(m-1)
else: print(m)
elif x==-a:
if y==a: print(m+1)
else:
print(m+1)
elif y==a:
print(m+1)
elif y==-a:
print(m+3)
```
No
| 4,513 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Submitted Solution:
```
x,y=tuple(map(int,input().split()))
if(x==0 and y==0):
print(0)
elif(x>=0 and y>=-x+1 and y<x):
if(y==-x+1):
print(4*(x-1))
else:
print(4*(x-1)+1)
elif(y>=0 and y!=-x):
if(y==x):
print(4*(abs(y)-1)+1)
else:
print(4*(abs(y)-1)+2)
elif(x<=0 and y!=x and y<abs(x) and y>=-abs(x)+1):
if(y==-x):
print(4*(abs(x)-1)+2)
else:
print(4*(abs(x)-1)+1+2)
else:
if(y==x):
print(4*(abs(y)-1)+3)
else:
print(4*(abs(y)-1)+1+3)
```
No
| 4,514 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
Input
The first line contains two space-separated integers x and y (|x|, |y| β€ 100).
Output
Print a single integer, showing how many times Valera has to turn.
Examples
Input
0 0
Output
0
Input
1 0
Output
0
Input
0 1
Output
2
Input
-1 -1
Output
3
Submitted Solution:
```
'''input
0 0
'''
def nextStep(x,y):
if x == 0 and y == 0:
return (1,0)
if x == 1 and y == 0:
return (1,1)
if x > 0 and y > 0:
return (-x, y)
if x < 0 and y > 0:
return (x, -y)
if x < 0 and y < 0:
return (-x + 1, y)
if x > 0 and y < 0:
return (x, -y + 1)
def main():
a, b = map(int, input().split())
pos = (0,0)
turns = 0
if(a == 1 and b == 0):
print(0)
return
while(pos[0] < a or pos[1] < b):
pos = nextStep(pos[0], pos[1])
turns += 1
print(turns)
if __name__ == "__main__":
main()
```
No
| 4,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Tags: combinatorics, math
Correct Solution:
```
input_string = input()
n = int(input())
len_tmp = len(input_string)
const = 1000000007
def fast_pow(a, b, mod):
c=bin(b)[2:]
result=1
for i in c:
result = (result*result * a**int(i))%mod
return result
def inverse(a, mod):
#mod-ΠΏΡΠΎΡΡΠΎΠ΅
return fast_pow(a, mod-2, mod)
#-------------------------------
num = 0
tmp = 1
"""
for i in range(len_tmp):
if int(input_string[i])%5==0:
num = (num + fast_pow(2, i, const))
"""
for i in range(len_tmp):
if int(input_string[i])%5==0:
num = (num + tmp)
tmp=(tmp*2)%const
num %= const
l = fast_pow(2, len_tmp, const)
print((num*(fast_pow(l, n, const)-1)*inverse(l-1, const))%const)
```
| 4,516 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Tags: combinatorics, math
Correct Solution:
```
A = input()
n = int(input())
m = 1000000007
a = len(A)
x = pow(2,a*n,m)-1+m
y = pow(2,a,m)-1+m
f = x*pow(y,m-2,m)%m
s = 0
for r in range(a):
if A[r] in '05':
s = (s+pow(2,r,m))%m
print((s*f)%m)
```
| 4,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Tags: combinatorics, math
Correct Solution:
```
mod = 1000000007
#gcd(a, m) = 1
def inv_mod(a, m):
a %= m
return pow(a, m-2, m)
a = input()
k = int(input())
t = len(a)
d = 0
for i, c in enumerate(a):
if not int(c) % 5:
d += pow(2, i, mod)
d %= mod
print(d*(pow(2, k*t, mod)-1)*inv_mod(pow(2, t, mod)-1, mod)%mod)
```
| 4,518 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Tags: combinatorics, math
Correct Solution:
```
n=input()
k=int(input())
X=list(n)
index=[]
mo=1000000007
for i in range(len(X)):
if X[i]=="0" or X[i]=="5":
index.append(i)
ans=0
R=pow(2,len(X),mo)
for i in index:
ans=(ans+pow(2,i,mo))%mo
ans=(ans*(pow(R,k,mo)-1)*pow(R-1,mo-2,mo))%mo
print(ans)
```
| 4,519 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Tags: combinatorics, math
Correct Solution:
```
a,k = input(), int(input())
n,m = len(a), 10 ** 9 + 7
ans = 0
t = (pow(2, k * n, m) - 1) * pow(pow(2, n, m) - 1, m - 2, m) % m
for i in range(n - 1, -1, -1):
if int(a[i]) % 5 == 0:
ans = (ans + pow(2, i, m) * t) % m
print(ans)
```
| 4,520 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Tags: combinatorics, math
Correct Solution:
```
s=input()
k=int(input())
p=10**9+7
n=len(s)
amodp = (pow(2,k*n,p)-1)%p
b1modp = pow ( (2**n) -1 , p-2 , p )
MOD = (amodp*b1modp) % p
ans=0
for i in range(len(s)):
if(s[i]=='5' or s[i]=='0'):
ans+=pow(2,i,10**9+7)
Ans=0
Ans+= ans*( MOD )
Ans%=p
##for i in range(k):
## Ans+=ans*pow(2,i*len(s),10**9+7)
print(Ans)
##x^k - 1
##---------
##x - 1
##
##
##x = 2**n
##
##2^kn - 1
##---------
##2^n - 1
##
##amodp = (pow(2,k*n,p)-1)%p
##
##b1modp = pow ( 2**k-1 , p-2 , p )
##
##MOD = (amodp*b1modp) % p
##
##
##
##(a / b) mod p = ((a mod p) * (b^(-1) mod p)) mod p
##
##b^(-1) mod p = b^(p - 2) mod p
```
| 4,521 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Tags: combinatorics, math
Correct Solution:
```
mod = 1000000007
def egcd(a, b):
d = a
if b != 0:
d, y, x = egcd(b, a%b)
y -= (a // b) * x
return d, x, y
else:
return a, 1, 0
def inv(a, m):
d, x, y = egcd(a, m)
return (m+x%m)%m
a = input()
k = int(input())
t = len(a)
d = 0
for i, c in enumerate(a):
if not int(c) % 5:
d += pow(2, i, mod)
d %= mod
d %= mod
print(d*(pow(2, k*t, mod)-1)*inv((pow(2, t, mod)-1)%mod, mod)%mod)
```
| 4,522 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Tags: combinatorics, math
Correct Solution:
```
t, k = input(), int(input())
s, n, d = 0, 1, 1000000007
for i in t:
if i in '05': s += n
n = (n << 1) % d
p = (pow(n, k, d) - 1) * pow(n - 1, d - 2, d)
print(((p % d) * (s % d)) % d)
```
| 4,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Submitted Solution:
```
mod = 1000000007
#gcd(a, m) = 1
def inv_mod(a, m):
a %= m
return pow(a, m-2, m)
a = input()
k = int(input())
t = len(a)
d = 0
for i, c in enumerate(a):
if not int(c) % 5:
d += pow(2, i, mod)
d %= mod
print(d*(pow(2, (k*t)%(mod-1), mod)-1)*inv_mod(pow(2, t, mod)-1, mod)%mod)
```
Yes
| 4,524 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Submitted Solution:
```
s=input()
k=int(input())
N=len(s)
m=1000000007
a=m+1-pow(2,N*k,m)
b=m+1-pow(2,N,m)
l=(a*pow(b,m-2,m))%m
p=0
for i in range(N):
if s[i] in ('0','5'):
p=(p+pow(2,i,m))
print((p*l)%m)
```
Yes
| 4,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Submitted Solution:
```
def invmod( x , y , MOD ):
return (x*pow(y,MOD-2,MOD))%MOD
s=input()
k=int(input())
n=len(s)
MOD=10**9+7
sumG = invmod( pow(2,k*n,MOD)-1 , pow(2,n,MOD)-1 , MOD)
ans=0
for i in range(len(s)):
if(s[i]=='5' or s[i]=='0'):
ans+=pow(2,i,MOD)
ans*=sumG
print(ans%MOD)
```
Yes
| 4,526 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Submitted Solution:
```
import sys
fin = sys.stdin
M = 1000000007
def egcd(a, b):
d = a
if b != 0:
d, y, x = egcd(b, a % b)
y -= (a // b) * x
return d, x, y
else:
return a, 1, 0
def inv(a, m):
d, x, y = egcd(a, m)
return (m + x % m) % m
a = fin.readline().strip()
k = int(fin.readline())
n = len(a)
D = (inv(pow(2, n, M) - 1, M) * (pow(2, n * k, M) - 1)) % M
S = 0
for i in range(n):
if a[i] in ['0', '5']:
S = (S + pow(2, i, M)) % M
print((D * S) % M)
```
Yes
| 4,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Submitted Solution:
```
######### ## ## ## #### ##### ## # ## # ##
# # # # # # # # # # # # # # # # # # #
# # # # ### # # # # # # # # # # # #
# ##### # # # # ### # # # # # # # # #####
# # # # # # # # # # # # # # # # # #
######### # # # # ##### # ##### # ## # ## # #
"""
PPPPPPP RRRRRRR OOOO VV VV EEEEEEEEEE
PPPPPPPP RRRRRRRR OOOOOO VV VV EE
PPPPPPPPP RRRRRRRRR OOOOOOOO VV VV EE
PPPPPPPP RRRRRRRR OOOOOOOO VV VV EEEEEE
PPPPPPP RRRRRRR OOOOOOOO VV VV EEEEEEE
PP RRRR OOOOOOOO VV VV EEEEEE
PP RR RR OOOOOOOO VV VV EE
PP RR RR OOOOOO VV VV EE
PP RR RR OOOO VVVV EEEEEEEEEE
"""
"""
Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
import sys
input = sys.stdin.readline
read = lambda: map(int, input().split())
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;
def ceil(x):
if x != int(x):
x = int(x) + 1
return x
def factorial(x, m):
val = 1
while x>0:
val = (val * x) % m
x -= 1
return val
def fact(x):
val = 1
while x > 0:
val *= x
x -= 1
return val
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
## gcd function
def gcd(a,b):
if b == 0:
return a;
return gcd(b, a % b);
## lcm function
def lcm(a, b):
return (a * b) // math.gcd(a, b)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if k > n:
return 0
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b;
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
prime[0], prime[1] = False, False
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
# Euler's Toitent Function phi
def phi(n) :
result = n
p = 2
while(p * p<= n) :
if (n % p == 0) :
while (n % p == 0) :
n = n // p
result = result * (1.0 - (1.0 / (float) (p)))
p = p + 1
if (n > 1) :
result = result * (1.0 - (1.0 / (float)(n)))
return (int)(result)
def is_prime(n):
if n == 0:
return False
if n == 1:
return True
for i in range(2, int(n ** (1 / 2)) + 1):
if not n % i:
return False
return True
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
res = []
for i in range(2, int(x ** 0.5) + 1):
while x % i == 0:
res.append(i)
x //= i
if x != 1:
res.append(x)
return res
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
def factors(n):
res = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
res.append(i)
res.append(n // i)
return list(set(res))
## taking integer array input
def int_array():
return list(map(int, input().strip().split()));
def float_array():
return list(map(float, input().strip().split()));
## taking string array input
def str_array():
return input().strip().split();
def binary_search(low, high, w, h, n):
while low < high:
mid = low + (high - low) // 2
# print(low, mid, high)
if check(mid, w, h, n):
high = mid
else:
low = mid + 1
return low
## for checking any conditions
def check(time, m, assistants):
summ = 0
for p in assistants:
time_needed_with_rest = p[0] * p[1] + p[2]
time_needed_without_rest = p[0]
baloons_can_be_inflated = p[1]
summ += (time // time_needed_with_rest) * baloons_can_be_inflated
ntime = time % time_needed_with_rest
summ += min(ntime // time_needed_without_rest, baloons_can_be_inflated)
return summ >= m
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
from itertools import permutations
import math
import bisect as bis
import random
import sys
def solve():
a = input().rstrip()
k = int(input())
s = 0
for i in range(len(a)):
if a[i] == '5' or a[i] == '0':
s += 2 ** i
# print(s, (2 ** (len(a) * k) - 1) // (2 ** len(a) - 1), len(a), k)
print((s * (power(2, (len(a) * k) - 1, MOD) // power(2, len(a) - 1, MOD))) % MOD)
if __name__ == '__main__':
for _ in range(1):
solve()
# fin_time = datetime.now()
# print("Execution time (for loop): ", (fin_time-init_time))
```
No
| 4,528 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Submitted Solution:
```
t, k = input(), int(input())
n, d = len(t), 1000000007
def f(i): return ((1 << i) * (pow(2, k * n, d) - 1) * pow((1 << n) - 1, d - 2, d)) % d
print(sum(f(i) for i in range(n) if t[i] in '05'))
```
No
| 4,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Submitted Solution:
```
input_string = input()
n = int(input())
len_tmp = len(input_string)
const = 1000000007
def fast_pow(a, b, mod):
c=bin(b)[2:]
result=1
for i in c:
result = (result**2 * a**int(i))%mod
return result
def inverse(a, mod):
#mod-ΠΏΡΠΎΡΡΠΎΠ΅
return fast_pow(a, mod-2, mod)
#-------------------------------
num = 0
for i in range(len_tmp):
if int(input_string[i])%5==0:
num = (num + fast_pow(2, i, const))%const
l = fast_pow(2, len_tmp, const)
print((num*(fast_pow(l, n, const)-1)*inverse(l, const))%const)
```
No
| 4,530 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
Input
In the first line you're given a string a (1 β€ |a| β€ 105), containing digits only. In the second line you're given an integer k (1 β€ k β€ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
Output
Print a single integer β the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
Note
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Submitted Solution:
```
def power(a,b):
r = a
val = 1
while b>0:
if b%2==1:
val = val*r
r = r*r
b= b//2
return val
s = input()
k = int(input())
si = len(s)
val = power(2,si)
x = val//2
val = (power(val,k) - 1)//(val-1)
ans = 0
for i in range(si-1,-1,-1):
if s[i]=='0' or s[i]=='5':
ans+=val*(x)
x = x//2
print(ans)
```
No
| 4,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are a set of points S on the plane. This set doesn't contain the origin O(0, 0), and for each two distinct points in the set A and B, the triangle OAB has strictly positive area.
Consider a set of pairs of points (P1, P2), (P3, P4), ..., (P2k - 1, P2k). We'll call the set good if and only if:
* k β₯ 2.
* All Pi are distinct, and each Pi is an element of S.
* For any two pairs (P2i - 1, P2i) and (P2j - 1, P2j), the circumcircles of triangles OP2i - 1P2j - 1 and OP2iP2j have a single common point, and the circumcircle of triangles OP2i - 1P2j and OP2iP2j - 1 have a single common point.
Calculate the number of good sets of pairs modulo 1000000007 (109 + 7).
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of points in S. Each of the next n lines contains four integers ai, bi, ci, di (0 β€ |ai|, |ci| β€ 50; 1 β€ bi, di β€ 50; (ai, ci) β (0, 0)). These integers represent a point <image>.
No two points coincide.
Output
Print a single integer β the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
10
-46 46 0 36
0 20 -24 48
-50 50 -49 49
-20 50 8 40
-15 30 14 28
4 10 -4 5
6 15 8 10
-20 50 -3 15
4 34 -16 34
16 34 2 17
Output
2
Input
10
30 30 -26 26
0 15 -36 36
-28 28 -34 34
10 10 0 4
-8 20 40 50
9 45 12 30
6 15 7 35
36 45 -8 20
-16 34 -4 34
4 34 8 17
Output
4
Input
10
0 20 38 38
-30 30 -13 13
-11 11 16 16
30 30 0 37
6 30 -4 10
6 15 12 15
-4 5 -10 25
-16 20 4 10
8 17 -2 17
16 34 2 17
Output
10
Submitted Solution:
```
from fractions import Fraction
from collections import defaultdict
MOD = 10**9 + 7
n, p = int(input()), []
for yo in range(n):
a, b, c, d = map(int, input().split())
down = a * a * d * d + b * b * c * c
p.append((Fraction(a * b * d * d, down), Fraction(c * d * b * b, down)))
mids = defaultdict(int)
for i in range(n):
for j in range(i + 1, n):
mids[(p[i][0] + p[j][0], p[i][1] + p[j][1])] += 1
ans = 0
for cnt in mids.values():
ans += pow(2, cnt, MOD) - cnt - 1
ans = ((ans % MOD) + MOD) % MOD
print(ans)
```
No
| 4,532 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
Input
The single line contains integers p, x (1 β€ p β€ 106, 1 β€ x β€ 9).
Output
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
Examples
Input
6 5
Output
142857
Input
1 2
Output
Impossible
Input
6 4
Output
102564
Note
Sample 1: 142857Β·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
Tags: math
Correct Solution:
```
p,k = input().split()
p = int (p)
k = int (k)
y = 10*k -1
x = ((10 ** (p-1)) - k) % y
b = True
for i in range(k,10):
if( (x*i % y) == 0):
#z = (x*i) // y
#print(z*10 + i)
z = i*10
while( (z-i)%y ):
z *= 10
part = str ((z-i)//y)
print(part * (p//len(part)))
b= False
break
if(b):
print("Impossible")
```
| 4,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
Input
The single line contains integers p, x (1 β€ p β€ 106, 1 β€ x β€ 9).
Output
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
Examples
Input
6 5
Output
142857
Input
1 2
Output
Impossible
Input
6 4
Output
102564
Note
Sample 1: 142857Β·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
Tags: math
Correct Solution:
```
p, k = map(int, input().split())
u = 10 * k - 1
v = pow(10, p - 1, u) - k
for y in range(k, 10):
if (y * v) % u == 0:
q = d = 9 * y
while q % u: q = 10 * q + d
q = str(q // u)
print(q * (p // len(q)))
break
else: print('Impossible')
# Made By Mostafa_Khaled
```
| 4,534 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
Input
The single line contains integers p, x (1 β€ p β€ 106, 1 β€ x β€ 9).
Output
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
Examples
Input
6 5
Output
142857
Input
1 2
Output
Impossible
Input
6 4
Output
102564
Note
Sample 1: 142857Β·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
Tags: math
Correct Solution:
```
p, k = map(int, input().split())
u = 10 * k - 1
v = pow(10, p - 1, u) - k
for y in range(k, 10):
if (y * v) % u == 0:
q = d = 9 * y
while q % u: q = 10 * q + d
q = str(q // u)
print(q * (p // len(q)))
break
else: print('Impossible')
```
| 4,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
Input
The single line contains integers p, x (1 β€ p β€ 106, 1 β€ x β€ 9).
Output
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
Examples
Input
6 5
Output
142857
Input
1 2
Output
Impossible
Input
6 4
Output
102564
Note
Sample 1: 142857Β·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
Submitted Solution:
```
p, n = map(int, input().split())
ok = 0
for i in range(1, 10):
x = (i * 10 ** (p - 1) - n * i) / (n * 10 - 1)
if x == int(x) and (len(str(int(x))) + len(str(i))) == p:
print('%d%d' % (int(x), i))
ok = 1
break
if not ok:
print('Impossible')
```
No
| 4,536 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
Input
The single line contains integers p, x (1 β€ p β€ 106, 1 β€ x β€ 9).
Output
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
Examples
Input
6 5
Output
142857
Input
1 2
Output
Impossible
Input
6 4
Output
102564
Note
Sample 1: 142857Β·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
Submitted Solution:
```
p,x=map(int,input().split())
c=0
for i in range (10**(p-1),10**p):
y=(i%10)*10**(p-1)
z=i//10
if (y+z)==x*i:
print(i)
c=c+1
break
if c==0:
print("impossible")
```
No
| 4,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
Input
The single line contains integers p, x (1 β€ p β€ 106, 1 β€ x β€ 9).
Output
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
Examples
Input
6 5
Output
142857
Input
1 2
Output
Impossible
Input
6 4
Output
102564
Note
Sample 1: 142857Β·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
Submitted Solution:
```
import math
s = input()
s = s.split(' ')
p = s[0]
x = s[1]
p = int(p)
x = int(x)
if p == 1 and x == 1:
print (0)
else:
nem = math.pow(10,p-1) - x
den = 10*x - 1
flag = True
for i in range(1,10,1):
ans = i*nem/den;
if ans.is_integer() and len(str(int(ans))) == p-1:
print(str(int(ans)) + str(i))
global flag
flag = False
break
if flag:
print("Impossible")
```
No
| 4,538 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly p decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
Input
The single line contains integers p, x (1 β€ p β€ 106, 1 β€ x β€ 9).
Output
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
Examples
Input
6 5
Output
142857
Input
1 2
Output
Impossible
Input
6 4
Output
102564
Note
Sample 1: 142857Β·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
Submitted Solution:
```
p,x=map(int,input().split())
t=pow(10,p)-1
t2=pow(10,p-1)
ok=0;
for d in range(1,9):
n=(d*t)
if n%(10*x-1)==0:
n//=(10*x-1)
n2=(n-d)//10+d*t2
if (n-d)%10==0:
n*=x
if n==n2 and n>0 and n2>0:
print(n)
ok=1
break;
if ok==0:
print("Impossible")
```
No
| 4,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
import sys
import math
import collections
import heapq
import decimal
input=sys.stdin.readline
n,k=(int(i) for i in input().split())
if(n*k>(n*(n-1))//2):
print(-1)
else:
print(n*k)
for i in range(1,n+1):
c=0
if(i==n):
j=1
else:
j=i+1
while(c<k):
print(i,j)
if(j==n):
j=1
else:
j+=1
c+=1
```
| 4,540 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
#code by AanchalTiwari
n, k = map(int, input().split())
if n < 2 * k + 1:
print(-1)
else:
print(n*k)
for i in range(1, n + 1):
c = 1
while c <= k:
a = i
b = i+c
if i + c > n:
a = i
b = (i+c) % n
print(a, b)
c = c + 1
```
| 4,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n,k=map(int,input().split())
if n<2*k+1:
print(-1)
else:
print(n*k)
l=range(1,n+1)
x=n-k
for i in range(x):
v=l[i]
for z in range(k):
print(v,v+1+z)
for i in range(x,n):
v=l[i]
for z in range(k):
if k-(n-v)>z:
print(v,z+1)
if z+1<=n-v:
print(v,v+1+z)
```
| 4,542 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
from sys import stdin,stdout
from collections import *
from math import ceil, floor , log, gcd
st=lambda:list(stdin.readline().strip())
li=lambda:list(map(int,stdin.readline().split()))
mp=lambda:map(int,stdin.readline().split())
inp=lambda:int(stdin.readline())
pr=lambda n: stdout.write(str(n)+"\n")
mod=1000000007
INF=float('inf')
def solve():
n,k=mp()
x= (n*(n-1)) >>1
if n*k>x:
pr(-1)
return
ans=[]
for i in range(1,n+1):
for j in range(i+1,i+k+1):
if j==n:
ans.append((i,n))
else:
ans.append((i,j%n))
print(len(ans))
for i in ans:
print(*i)
for _ in range(1):
solve()
```
| 4,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n,k=map(int,input().split())
if(k>(n-1)//2):
print(-1)
else:
print(n*k)
for i in range(1,n+1):
for j in range(k):
print(i,(i+j)%n+1)
```
| 4,544 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n, k = map(int, input().split())
if k > (n - 1) // 2:
print(-1)
else:
print(n * k)
for i in range(n):
for j in range(k):
l = i
r = (l + j + 1)
print(l + 1, r%n + 1)
```
| 4,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n,k=map(int,input().split())
if n<2*k+1:
print(-1)
else:
print(n*k)
for i in range(1,n+1):
for z in range(k):
print(i,(i+z)%n+1)
```
| 4,546 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
import sys,os,io
import math,bisect,operator
inf,mod = float('inf'),10**9+7
# sys.setrecursionlimit(10 ** 6)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
I = lambda : int(sys.stdin.buffer.readline())
Neo = lambda : list(map(int, sys.stdin.buffer.readline().split()))
n,k = Neo()
if 2*k > n-1:
print(-1)
else:
print(n*k)
for i in range(1,n+1):
for j in range(i+1,k+i+1):
if j > n:
j = j%n
print(i,j)
```
| 4,547 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Submitted Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
def main():
n,k=map(int,input().split())
if n<(k<<1)+1:
print(-1)
exit()
# each team will hae 2k edges
print(n*k)
for i in range(1,n+1):
j=i+1
z=k
while z:
if j==n+1:
j=1
print(i,j)
z-=1
j+=1
#----------------------------------------------------------------------------------------
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
```
Yes
| 4,548 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Submitted Solution:
```
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
#def input(): return sys.stdin.readline().strip()
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
ilelec = lambda: map(int1,input().split())
alelec = lambda: list(map(int1, input().split()))
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)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
n,k = ilele()
if not(2*k <= n-1):
print(-1)
else:
print(n*k)
for i in range(1,n+1):
for j in range(i+1,i+1+k):
if j > n:
j = j - n
print(i,j)
```
Yes
| 4,549 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Submitted Solution:
```
n, k = [int(i) for i in input().split()]
if k > n // 2 or n < 3 or n == 2*k:
print(-1)
exit()
print(n * k)
arr = list(range(1, n + 1)) + list(range(1, n // 2 + 1))
for i in range(arr[arr.index(max(arr))] ):
for j in range(1, k + 1):
print(arr[i], arr[j + i])
```
Yes
| 4,550 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Submitted Solution:
```
n, k = map(int, input().strip().split())
if 2 * k > (n - 1):
print('-1')
else:
r = [str(n * k)]
for i in range(1, n+1):
for j in range(k):
r.append(str(i) + ' ' + str((i + j) % n + 1))
print('\n'.join(r))
```
Yes
| 4,551 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
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")
##########################################################
#from collections import Counter
#from fractions import Fraction
#s=iter(input())
# for _ in range(int(input())):
#from collections import deque
# n=int(input())
# n,k=map(int,input().split())
# arr=list(map(int,input().split()))
#ls=list(map(int,input().split()))
#for i in range(m):
from collections import Counter
#for i in range(int(input())):
#n=int(input())
#n,k=map(int,input().split())
#arr = list(map(int, input().split()))
#for i in range(int(input())):
n,k=map(int,input().split())
if n-k<=k:
print(-1)
else:
print(n*(n-1)//2)
for i in range(1,n+1):
var=i+1
for j in range(k):
var=var%(n+1)
if var==0:
var+=1
print(i, var)
var+=1
```
No
| 4,552 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Submitted Solution:
```
n, k = [int(i) for i in input().split()]
if k > n // 2:
print(-1)
exit()
print(n * k)
arr = list(range(1, n + 1)) + list(range(1, n // 2 + 1))
for i in range(arr[arr.index(max(arr))] ):
for j in range(1, k + 1):
print(arr[i], arr[j + i])
```
No
| 4,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Submitted Solution:
```
from sys import stdin,stdout
from collections import *
from math import ceil, floor , log, gcd
st=lambda:list(stdin.readline().strip())
li=lambda:list(map(int,stdin.readline().split()))
mp=lambda:map(int,stdin.readline().split())
inp=lambda:int(stdin.readline())
pr=lambda n: stdout.write(str(n)+"\n")
mod=1000000007
INF=float('inf')
def solve():
n,k=mp()
pr(n*k)
ans=[]
for i in range(1,n+1):
c=0
for j in range(1,n+1):
if c==k:
break
if i!=j:
ans.append((i,j))
c+=1
for i in ans:
print(*i)
for _ in range(1):
solve()
```
No
| 4,554 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Submitted Solution:
```
n,k = map(int,input().split())
s=[]
if (k >= n/2):
print(-1)
else:
print(n*k)
for i in range(n):
for j in range(k):
a = i+1
b = (i+j+2)%n
s.append("%d %d"%(a,b))
print("\n".join(s))
```
No
| 4,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
# HEY STALKER
n, m = map(int, input().split())
l = list(map(int, input().split()))
ans = 0
for t in range(m):
x, y, c = map(int, input().split())
ans = max(ans, (l[x-1] + l[y-1]) / c)
print(ans)
```
| 4,556 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
import math
def solve():
n, m = [int(i) for i in input().split()]
vw = [int(i) for i in input().split()]
M = 0.0
for _ in range(m):
a, b, c = [int(i) for i in input().split()]
M = max(M, (vw[a - 1] + vw[b - 1]) / c)
print(M)
if __name__ == '__main__':
solve()
```
| 4,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
v, e = map(int, input().split())
vertex = list(map(int, input().split()))
ret = 0.0
for i in range(e):
a, b, c = map(int, input().split())
a -= 1;
b -= 1;
ret = max(ret, (vertex[a] + vertex[b]) / c)
print(ret)
```
| 4,558 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
n,m = map(int,input().split())
a = list(map(int,input().split()))
ans = 0
for i in range(m):
ax,bx,x = map(int,input().split())
ans = max(ans,(a[ax-1]+a[bx-1])/x)
print(ans)
```
| 4,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
n,m=map(int,input().split());a=list(map(int,input().split()));o=0.0
for i in range(m):
x,y,c=map(int,input().split());o=max(o,(a[x-1]+a[y-1])/c)
print(o)
# Made By Mostafa_Khaled
```
| 4,560 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
nodes , edges = map(int,input().split())
x=list(map(int,input().split()))
error =0
for i in range(edges):
a,b,c=map(int,input().split())
error = max(error , (x[a-1]+x[b-1])/c)
print(error)
```
| 4,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
n, m = map(int, input().split())
x = [int(i) for i in input().split()]
edge = []
val = 0
for i in range(m):
a, b, c = map(int, input().split())
val = max((x[a-1]+x[b-1])/c, val)
print(val)
```
| 4,562 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
n, m = map(int, input().split())
t, v = 0, [0] + list(map(int, input().split()))
for i in range(m):
x, y, d = map(int, input().split())
t = max(t, (v[x] + v[y]) / d)
print(t)
```
| 4,563 |
Provide tags and a correct Python 2 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Tags: greedy, math
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
n,m=in_arr()
l=in_arr()
ans=0.0
for i in range(m):
a,b,c=in_arr()
temp=(l[a-1]+l[b-1])/float(c)
ans=max(ans,temp)
pr_num(float(ans))
```
| 4,564 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
n, m = map(int, input().split())
v = list(map(int, input().split()))
mini = 0
for i in range(m):
a, b, c = map(int, input().split())
mini = max(mini, (v[a-1]+v[b-1])/c)
print(mini)
```
Yes
| 4,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
import sys
from collections import defaultdict
import math
from heapq import *
import itertools
MAXNUM = math.inf
MINNUM = -1 * math.inf
ASCIILOWER = 97
ASCIIUPPER = 65
pq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = "<removed-task>" # placeholder for a removed task
counter = itertools.count() # unique sequence count
def add_task(task, priority=0):
"Add a new task or update the priority of an existing task"
if task in entry_finder:
remove_task(task)
count = next(counter)
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry)
def remove_task(task):
"Mark an existing task as REMOVED. Raise KeyError if not found."
entry = entry_finder.pop(task)
entry[-1] = REMOVED
def pop_task():
"Remove and return the lowest priority task. Raise KeyError if empty."
while pq:
priority, count, task = heappop(pq)
if task is not REMOVED:
del entry_finder[task]
return task
raise KeyError("pop from an empty priority queue")
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
sys.stdout.write("%.15f" % (ans))
def findParent(a, parents):
cur = a
while parents[cur] != cur:
cur = parents[cur]
parents[a] = cur # reduction of search time on next search
return cur
def union(a, b, parents):
parents[b] = a
def solve(nodeList, edgeList, edgeHeap):
parents = [i for i in range(nodeList)]
minTreeEdges = []
totalEdges = defaultdict(int)
# Get min spanning tree
while edgeHeap:
eVal, n1, n2 = heappop(edgeHeap)
n1Parent = findParent(n1, parents)
n2Parent = findParent(n2, parents)
if n1Parent != n2Parent:
union(n1Parent, n2Parent, parents)
totalEdges[n1] += 1
totalEdges[n2] += 1
add_task(n1, totalEdges[n1])
add_task(n2, totalEdges[n2])
minTreeEdgeList[n1] = (n2, eVal)
minTreeEdgeList[n2] = (n1, eVal)
# prune min spanning tree starting from leaves
def readinput():
heap = []
v, e = getInts()
nodes = [0] + list(getInts())
mx = 0
for i in range(e):
n1, n2, e = getInts()
mx = max(mx, (nodes[n1] + nodes[n2]) / e)
printOutput(mx)
readinput()
```
Yes
| 4,566 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
n,m=map(int, input().split())
w=list(map(int, input().split()))
ans=0.0
for i in range(m):
u,v,c=map(int, input().split())
ans=max(ans, round( (w[u-1]+w[v-1])/c,9))
print(ans)
```
Yes
| 4,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
from sys import stdin
input = stdin.readline
n, m = map(int, input().split())
arr = [int(i) for i in input().split()]
res = 0.0
for _ in range(m):
a, b, c = map(int, input().split())
if c: res = max(res, (arr[a-1] + arr[b-1]) / c)
print(res)
```
Yes
| 4,568 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
n,m=map(int, input().split())
w=list(map(int, input().split()))
ans=0.0
for i in range(m):
u,v,c=map(int, input().split())
ns=max(ans, round( (w[u-1]+w[v-1])/c,9))
print(ans)
```
No
| 4,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
from sys import *
setrecursionlimit(200000000)
inp = lambda : stdin.readline()
n,m = 0,0
dx = [1,-1,0,0]
dy = [0,0,1,-1]
visited = [ [0 for j in range(104)] for i in range(104)]
def dfs(a,x,y,w):
if visited[x][y] == 1: return
visited[x][y] = 1
if a[x][y] == '.': a[x][y] = w
w2 = 'W' if w == 'B' else 'B'
for i in range(4):
if 0 <= dx[i] + x < n and 0 <= dy[i] + y < m:
dfs(a,dx[i]+x,dy[i]+y,w2)
def main():
global n,m
n,m = map(int,inp().split())
a = [ ['-' for j in range(m)] for i in range(n)]
for i in range(n):
s = inp()[:-1]
a[i] = [c for c in s]
dfs(a,0,0,'B')
for i in a:
print("".join(i))
if __name__ == "__main__":
main()
```
No
| 4,570 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 β€ n β€ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 β€ xi β€ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 β€ ai < bi β€ n; 1 β€ ci β€ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
n,m=map(int, input().split())
g={}
w=list(map(int, input().split()))
edgeweight={}
for i in range(m):
u,v,c=map(int, input().split())
if u in g:
g[u].append(v)
else:
g[u]=[v]
# u,v=v,u
# if u in g:
# g[u].append(v)
# else:
# g[u]=[v]
edgeweight[(u,v)]=c
#edgeweight[(v,u)]=c
ans=0.0
vis=[0]*(n+1)
for i in range(1,n+1):
if not vis[i] and i in g.keys():
for j in g[i]:
vis[j]=1
ans=max(ans, round( (w[i-1]+w[j-1])/edgeweight[(i,j)],10))
print(ans)
```
No
| 4,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Tags: brute force, math
Correct Solution:
```
n,a,b = map(int, input().split())
if a*b > 6*n:
print(a*b)
print(str(a)+" "+str(b))
exit()
rev = False
if a>b:
rev = True
tmp = a
a = b
b = tmp
size = 6*n
while True:
flag = False
small = 0
i = a
while i*i < size:
if ((size)%i == 0) and ((size)/i >= b):
flag = True
small = i
break
i += 1
if flag:
if rev:
print(size)
print(str(size//small)+" "+str(small))
else:
print(size)
print(str(small)+" "+str(size//small))
exit()
else:
size += 1
```
| 4,572 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Tags: brute force, math
Correct Solution:
```
from math import *
n,a,b = map(int,input().split())
ans = (10000005700000,1000000000064000)
ansp = 10**55
if a*b>=6*n:
ans = (a,b)
ansp = a*b
for x in range(int(sqrt(6*n)*1.33)):
yy = max(0,ceil((6*n-a*b-b*x)/(a+x))-1)
for y in range(yy,yy+3):
if 6*n<=(a+x)*(b+y)<ansp:
ansp=(a+x)*(b+y)
ans = (a+x,b+y)
a,b = b,a
for x in range(int(sqrt(6*n)*1.44)):
yy = max(0,ceil((6*n-a*b-b*x)/(a+x))-1)
for y in range(yy,yy+3):
if 6*n<=(a+x)*(b+y)<ansp:
ansp=(a+x)*(b+y)
ans = (b+y,a+x)
print (ansp)
print(*ans)
```
| 4,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Tags: brute force, math
Correct Solution:
```
n,a,b = [int(x) for x in input().split()]
n *= 6
if a*b >= n:
print(a*b)
print(a,b)
else:
reverse = False
if b < a:
reverse = True
a,b = b,a
low = float('inf')
lowNums = [0,0]
for x in range(a, min(int(n**0.5),n//b)+1):
second = n//x
if n%x != 0:
second += 1
#print(x,second)
if second*x < low:
low = second*x
lowNums = [x,second]
if reverse:
print(low)
print(lowNums[1], lowNums[0])
else:
print(low)
print(lowNums[0], lowNums[1])
```
| 4,574 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Tags: brute force, math
Correct Solution:
```
import math
line = input().split()
n = int(line[0])
a = int(line[1])
b = int(line[2])
desired = 6 * n
if a * b >= desired:
print(a * b)
print(a, b)
else:
smallest = min(a, b)
largest = max(a,b)
num = desired
found = False
while True:
i = 0
midpoint = math.floor(math.sqrt(num))
while True:
current = midpoint - i
if current < smallest:
break
if num % current == 0 and num // current >= largest:
found = True
desired = num
newSmallest = current
newLargest = num // current
break
i += 1
if found:
break
num += 1
print(desired)
if a < b:
print(newSmallest, newLargest)
else:
print(newLargest, newSmallest)
```
| 4,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Tags: brute force, math
Correct Solution:
```
import sys
from math import ceil
input=sys.stdin.readline
n,a,b=map(int,input().split())
if 6*n<=a*b:
print(a*b)
print(a,b)
exit()
p=6*n
flag=False
if a>b:
a,b=b,a
flag=True
ans=10**18
ans_a,ans_b=-1,-1
for i in range(1,int(p**0.5)+1):
u=i;v=ceil(p/i) #u<=v,a<=b
for rep in range(2):
if a<=u and b<=v:
if u*v<ans:
ans_a=u
ans_b=v
ans=u*v
elif a<=u and v<=b:
if a<=ceil(p/b) and b*ceil(p/b)<ans:
ans_a=ceil(p/b)
ans_b=b
ans=ceil(p/b)*b
elif a>=u and b<=v:
if b<=ceil(p/a) and a*ceil(p/a)<ans:
ans_a=a
ans_b=ceil(p/a)
ans=a*ceil(p/a)
u,v=v,u
print(ans)
if flag:
print(ans_b,ans_a)
else:
print(ans_a,ans_b)
```
| 4,576 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Tags: brute force, math
Correct Solution:
```
import sys
def fastio():
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
def debug(*var, sep = ' ', end = '\n'):
print(*var, file=sys.stderr, end = end, sep = sep)
INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from math import ceil, log2
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
n, a, b = I()
area = 6 * n
ans = INF
ansa, ansb = a, b
swap = 0
if b < a:
swap = 1
a, b = b, a
iter = 0
for i in range(a, INF):
j = max(b, ceil(area / i))
if j * i >= area and j * i <= ans:
ans = j * i
ansa = i
ansb = j
iter += 1
if iter >= 100000:
break
print(ans)
if swap:
ansa, ansb = ansb, ansa
print(ansa, ansb)
```
| 4,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Tags: brute force, math
Correct Solution:
```
import sys
import math
def calc():
global ans, a, b
n, a, b = map(int, input().strip().split(' '))
n *= 6
if a*b >= n:
print("%i %i %i" % (a*b, a, b))
sys.exit(0)
m = int(math.sqrt(n)) + 10
ans = (10**15, 0, 0)
for i in range(m):
k = max(b, n // (a + i))
if k*(a + i) < n:
tmp = ( (k + 1)*(a + i), a + i, k + 1)
else:
tmp = ( (k + 0)*(a + i), a + i, k)
if tmp < ans: ans = tmp
for i in range(m):
k = max(a, n // (b + i))
if k*(b + i) < n:
tmp = ( (k + 1)*(b + i), k + 1, b + i)
else:
tmp = ( (k + 0)*(b + i), k, b + i)
if tmp < ans: ans = tmp
print("%i %i %i" % ans)
```
| 4,578 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Tags: brute force, math
Correct Solution:
```
"""
Codeforces Contest 266 Div 2 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
def ceildiv(a,b):
return a//b + (1 if a%b else 0)
def main():
n,a,b = read()
s = 6*n
if a*b >= s:
print(a*b)
print(a,b)
return
t = int((6*n) ** .5)
tgt = 9001*n
tgta = 0
tgtb = 0
for i in range(1, t+1):
c = ceildiv(s,i)
if a <= i and b <= c:
if tgt > i*c:
tgt = i*c
tgta = i
tgtb = c
if b <= i and a <= c:
if tgt > i*c:
tgt = i*c
tgtb = i
tgta = c
print(tgt)
print(tgta,tgtb)
################################### NON-SOLUTION STUFF BELOW
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0: return inputs
if mode == 1: return inputs.split()
if mode == 2: return list(map(int, inputs.split()))
def write(s="\n"):
if s is None: s = ""
if isinstance(s, list): s = " ".join(map(str, s))
s = str(s)
print(s, end="")
write(main())
```
| 4,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Submitted Solution:
```
import math
n, a, b = map(int, input().split())
origa = a; origb = b
if a > b:
a, b = b, a
a1, b1 = a, b
cur = 10**18
if a*b >= 6*n:
print(a*b)
print(a, b)
exit()
for x in range(a, int(math.sqrt(6*n)) + 2):
y = math.ceil(6*n / x)
if y <= b:
continue
if x*y < cur:
a1 = x; b1 = y
cur = x*y
if a1 < origa or b1 < origb:
a1, b1 = b1, a1
print(cur)
print(a1, b1)
```
Yes
| 4,580 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Submitted Solution:
```
import math
#input
n,a,b=map(int,input().split())
#variables
x=6*n-1
#main
if a*b>6*n:
print(a*b)
print(str(a)+' '+str(b))
quit()
while True:
x+=1
for i in range(min(a,b),math.floor(math.sqrt(x))+1):
if x%i==0:
if i>=a and x/i>=b:
print(x)
print(str(i)+' '+str(x//i))
quit()
if i>=b and x/i>=a:
print(x)
print(str(x//i)+' '+str(i))
quit()
```
Yes
| 4,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Submitted Solution:
```
#!/usr/bin/env python3
import math
n, a, b = [int(x) for x in input().split()]
area_required = 6*n
if a*b >= area_required:
print(str(a*b))
print(str(a) + " " + str(b))
else:
final_area = 2*area_required
if a > b:
switch = 1
temp = a
a = b
b = temp
else:
switch = 0
new_a = a
new_b = b
# for t_a in range(a, int(area_required/b)+2):
# t_b = max(math.ceil(area_required/t_a), b)
# temp_area = t_a * t_b
# if temp_area < final_area:
# final_area = temp_area
# new_a = t_a
# new_b = t_b
# if final_area == area_required:
# break
for t_a in range(a, b+1):
t_b = max(math.ceil(area_required/t_a), b)
temp_area = t_a * t_b
if temp_area < final_area:
final_area = temp_area
new_a = t_a
new_b = t_b
if final_area == area_required:
break
for t_a in range(b, int(math.sqrt(area_required))+2):
t_b = max(math.ceil(area_required/t_a), b)
temp_area = t_a * t_b
if temp_area < final_area:
final_area = temp_area
new_a = t_a
new_b = t_b
if final_area == area_required:
break
print(str(final_area))
if switch==0:
print(str(new_a) + " " + str(new_b))
else:
print(str(new_b) + " " + str(new_a))
```
Yes
| 4,582 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Submitted Solution:
```
n,a,b=map(int,input().split())
n*=6
if a*b>=n:
print(a*b)
print(a,b)
exit(0)
z=0
if b<a:
a,b=b,a
z=1
x,y=a,b
area=1e18+1
for i in range(a,int(n**0.5)+1):
tb=n//i
if i*tb<n:
tb+=1
if tb<b:continue
if i*tb<area:
area=i*tb
x,y=i,tb
if z:
x,y=y,x
print(area)
print(x,y)
```
Yes
| 4,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Submitted Solution:
```
n,a,b = list(map(int,input("").split()))
minSurface = n*6
swap = False
if(a<b):
b,a = a,b
swap = True
b,a = min(a,b), max(a,b)
smalla = a
mb = 1000000000000000000
ma = 1000000000000000000
for i in range(b,b+6,1):
if(smalla<int(minSurface/b)):
a = int(minSurface/b)
if(a!= minSurface/b):
a += 1
if(a*i<ma*mb):
ma = a
mb = i
if(swap):
mb,ma = ma,mb
print(ma*mb)
print(ma,mb)
"""
while(a*b<=minSurface):
if(b%6!=0):
b+=1
else:
break
if(a<int(minSurface/b)):
a = int(minSurface/b)
if(a!= minSurface/b):
a +=1
print(a*b)
print(a,b)
"""
```
No
| 4,584 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Submitted Solution:
```
n,a,b = [int(i) for i in input().split()]
if n*6 <= a*b:
print(a*b)
print(a,b)
else:
min_area = n*6
needed = n*6 - a*b
if needed%a == 0:
print(a*(b+needed//a))
print(a,b+needed//a)
elif needed%b == 0:
print(b * (a + needed // b))
print(a+needed // b, b)
else:
if min(n,6) > min(a,b) and max(n,6) > max(a,b):
print(n*6)
print(n,6)
```
No
| 4,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Submitted Solution:
```
n,a,b = list(map(int,input("").split()))
minSurface = n*6
b,a = min(a,b), max(a,b)
smalla = a
mb = 99999999
ma = 99999999
for i in range(b,b+6,1):
if(smalla<int(minSurface/b)):
a = int(minSurface/b)
if(a!= minSurface/b):
a +=1
if(a*i<ma*mb):
ma = a
mb = i
print(ma*mb)
print(ma,mb)
"""
while(a*b<=minSurface):
if(b%6!=0):
b+=1
else:
break
if(a<int(minSurface/b)):
a = int(minSurface/b)
if(a!= minSurface/b):
a +=1
print(a*b)
print(a,b)
"""
```
No
| 4,586 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for n students must have the area of at least 6n square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all n students could live in it and the total area of the room was as small as possible.
Input
The first line contains three space-separated integers n, a and b (1 β€ n, a, b β€ 109) β the number of students and the sizes of the room.
Output
Print three integers s, a1 and b1 (a β€ a1; b β€ b1) β the final area of the room and its sizes. If there are multiple optimal solutions, print any of them.
Examples
Input
3 3 5
Output
18
3 6
Input
2 4 4
Output
16
4 4
Submitted Solution:
```
import math
n, a, b=map(int, input().split())
n*=6
p, x, y=a*b, a, b
if p<n:
i=math.ceil((n)/a)
j=math.ceil((n)/b)
if i*a<j*b:
p, x, y=i*a, a, i
else:
p, x, y=j*b, j, b
if p>n:
s=math.floor(math.sqrt(n))
k=min(a, b)
for i in range(k, s+1):
if n//i<max(a,b):
break
if not n%i:
p, x, y=n, i, n//i
break
if (a>b and x<y) or (a<b and x>y):
x,y=y, x
print(p)
print(x, y)
```
No
| 4,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An n Γ n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
Input
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
Output
Print the remainder after dividing the required value by number mod.
Examples
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
Note
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
Tags: combinatorics, dp
Correct Solution:
```
n, m, mod = [int(x) for x in input().split()]
from functools import lru_cache
import sys
sys.setrecursionlimit(100000000)
@lru_cache(maxsize=None)
def rec(twos, ones):
global mod
if twos == 0 and ones == 0:
return 1
if twos == 1 and ones == 0:
return 0
else:
count = 0
# we can pick two from ones if there are at least two:
if (ones >= 2):
a = ones*(ones-1)//2
b = rec(twos, ones-2)
count += (a*b) % mod
if (ones >= 1 and twos >= 1):
a = ones*twos
b = rec(twos-1, ones)
count += (a*b) % mod
if (twos >= 2):
a = twos*(twos-1)//2
b = rec(twos-2, ones+2)
count += (a*b) % mod
return count % mod
# we read the beginning matrix and calculate the starting position
matrix = []
for i in range(0, m):
matrix.append([int(x) for x in input()])
twocount = 0
onecount = 0
for c in range(0, n):
# for each column count the number of ones in it
count = 0
for r in range(0, m):
# r is the row, c is the column
if (matrix[r][c] == 1):
count += 1
if count == 2:
twocount += 1
elif count == 1:
onecount += 1
ones = onecount
twos = n - onecount - twocount
print(rec(twos, ones))
```
| 4,588 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An n Γ n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
Input
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
Output
Print the remainder after dividing the required value by number mod.
Examples
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
Note
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
Tags: combinatorics, dp
Correct Solution:
```
from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
dp = [[-1 for i in range(505)] for j in range(505)]
def memo(row,z,o):
if(row == n):
if(z == 0 and o == 0):
return 1
else:
return 0
if(dp[z][o] != -1): return dp[z][o]
if(z > 1):
dp[z][o] += (z*(z-1)//2)*(memo(row+1,z-2,o+2))
dp[z][o] %= mod
if(z >= 1 and o >= 1):
dp[z][o] += (z*o)*(memo(row+1,z-1,o))
dp[z][o] %= mod
if(o > 1):
dp[z][o] += (o*(o-1)//2)*(memo(row+1,z,o-2))
dp[z][o] %= mod
#print(row,z,o,dp[z][o])
dp[z][o] += 1
dp[z][o] %= mod
return dp[z][o]%mod
n,m,mod = map(int,input().split())
a = []
for i in range(m):
s = list(input())
a.append(s)
#print(a)
ct = [0 for i in range(n)]
for i in range(m):
for j in range(n):
if(a[i][j] == '1'):
ct[j] += 1
z = ct.count(0)
o = ct.count(1)
ans = memo(m,z,o)
print(ans%mod)
```
| 4,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An n Γ n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
Input
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
Output
Print the remainder after dividing the required value by number mod.
Examples
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
Note
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
Tags: combinatorics, dp
Correct Solution:
```
a,b,mod = list(map(int, input().split()))
g = [2] * a
for i in range(b):
t = input()
for x, y in enumerate(t):
if y == '1':
g[x] -= 1
one = two = 0
for q in g:
if q < 0:
print(0)
exit(0)
if q == 1:
one+=1
if q == 2:
two+=1
mat = [[0]*600 for x in range(600)]
mat[0][0] = 1
#int(one, two)
for j in range(a + 1):
for i in range(a + 1):
if i-2>=0:
mat[i][j] += i*(i-1) // 2 * mat[i-2][j];
#print('in',i,j, mat[i][j], i*(i-1)//2, mat[i-2][j], i-2, mat[0][0])
if j-1>=0:
mat[i][j] += i*j * mat[i][j -1];
if j-2>=0 :
mat[i][j] += j *(j-1)//2 * mat[i+2][j -2];
mat[i][j] %= mod
#print(mat[2][0])
#print(mat[0][2])
print(mat[one][two])
```
| 4,590 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An n Γ n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
Input
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
Output
Print the remainder after dividing the required value by number mod.
Examples
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
Note
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
Tags: combinatorics, dp
Correct Solution:
```
# // DP
# // codeforces 489F Special Matrices
n = 0
m = 0
MOD = 0
cap = [0] * 505
ans = [[-1] * 505 for i in range(505)]
def f(one, two):
if one == 0 and two == 0:
return 1
if two > len(ans[one]):
print(str(one) + ' ' + str(two) + ' ' + len(ans[one]))
if ans[one][two] != -1:
return ans[one][two]
temp = 0
if two > 1:
x = two * (two-1) / 2 * f(one+2, two-2)
temp += x % MOD
if one > 1:
x = one * (one-1) / 2 * f(one-2, two)
temp += x % MOD
if two > 0 and one > 0:
x = one * two * f(one, two-1)
temp += x % MOD
temp = temp % MOD
ans[one][two] = temp
return temp
temp = input().split(' ')
n = int(temp[0])
m = int(temp[1])
MOD = int(temp[2])
for i in range(0, m):
cur = ''
cur = input()
for j in range(0, n):
if cur[j] == '1':
cap[j] += 1
n_one = 0;
n_two = 0;
for i in range(0, n):
if cap[i] == 0:
n_two += 1
if cap[i] == 1:
n_one += 1
print(int(f(n_one, n_two)))
# // F. Special Matrices
# // time limit per test
# // 1 second
# // memory limit per test
# // 256 megabytes
# // input
# // standard input
# // output
# // standard output
# // An nβΓβn square matrix is special, if:
# // it is binary, that is, each cell contains either a 0, or a 1;
# // the number of ones in each row and column equals 2.
# // You are given n and the first m rows of the matrix. Print the number of special nβΓβn matrices, such that the first m rows coincide with the given ones.
# // As the required value can be rather large, print the remainder after dividing the value by the given number mod.
# // Input
# // The first line of the input contains three integers n, m, mod (2ββ€βnββ€β500, 0ββ€βmββ€βn, 2ββ€βmodββ€β109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given mβΓβn table contains at most two numbers one.
# // Output
# // Print the remainder after dividing the required value by number mod.
# // Sample test(s)
# // Input
# // 3 1 1000
# // 011
# // Output
# // 2
# // Input
# // 4 4 100500
# // 0110
# // 1010
# // 0101
# // 1001
# // Output
# // 1
# // Note
# // For the first test the required matrices are:
# // 011
# // 101
# // 110
# // 011
# // 110
# // 101
# // In the second test the required matrix is already fully given, so the answer is 1.
```
| 4,591 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An n Γ n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
Input
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
Output
Print the remainder after dividing the required value by number mod.
Examples
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
Note
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
Submitted Solution:
```
n, m, od = map(int, input().split())
ones_in_c = [0 for i in range(n)]
for i in range(m):
inp = input()
for j in range(n):
ones_in_c[j] = ones_in_c[j]+1 if inp[j] == '1' else ones_in_c[j]
need2 = ones_in_c.count(0)
need1 = ones_in_c.count(1)
rows_left = n-m
dp = {}
def count_rows(need1, need2, rows_left):
global n, od
if (need1, need2, rows_left) in dp:
return dp[(need1, need2, rows_left)]
if rows_left == 1:
return 1
total = 0
if need1 >= 2:
total += rows_left*(rows_left-1)/2*count_rows(need1-2, need2, rows_left-1)
if need2 >=1 and need1 >= 1:
total += rows_left*(rows_left-1)/2*count_rows(need1, need2-1, rows_left-1)
if need2 >= 2:
total += rows_left*(rows_left-1)/2*count_rows(need1+2, need2-2, rows_left-1)
#print(need1, need2, rows_left, total)
return total % od
#print(need1, need2, rows_left)
if need2*2 + need1 != 2*rows_left:
print(0)
else:
if rows_left == 0:
print(1)
else:
print(int(count_rows(need1, need2, rows_left)))
```
No
| 4,592 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An n Γ n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
Input
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
Output
Print the remainder after dividing the required value by number mod.
Examples
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
Note
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
Submitted Solution:
```
n, m, mod = [int(x) for x in input().split()]
from functools import lru_cache
@lru_cache(maxsize=None)
def rec(twos, ones):
global mod
if twos == 0 and ones == 0:
return 1
if twos != 0 and ones == 0:
return 0
else:
count = 0
# we can pick two from ones if there are at least two:
if (ones >= 2):
a = ones*(ones-1)//2
b = rec(twos, ones-2)
count += (a*b) % mod
if (ones >= 1 and twos >= 1):
a = ones*twos
b = rec(twos-1, ones)
count += (a*b) % mod
return count % mod
# we read the beginning matrix and calculate the starting position
matrix = []
for i in range(0, m):
matrix.append([int(x) for x in input()])
twocount = 0
onecount = 0
for c in range(0, n):
# for each column count the number of ones in it
count = 0
for r in range(0, m):
# r is the row, c is the column
if (matrix[r][c] == 1):
count += 1
if count == 2:
twocount += 1
elif count == 1:
onecount += 1
ones = onecount
twos = n - onecount - twocount
print(rec(twos, ones))
```
No
| 4,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An n Γ n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
Input
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
Output
Print the remainder after dividing the required value by number mod.
Examples
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
Note
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
Submitted Solution:
```
n, m, od = map(int, input().split())
ones_in_c = [0 for i in range(n)]
for i in range(m):
inp = input()
for j in range(n):
ones_in_c[j] = ones_in_c[j]+1 if inp[j] == '1' else ones_in_c[j]
need2 = ones_in_c.count(0)
need1 = ones_in_c.count(1)
rows_left = n-m
dp = {}
def count_rows(need1, need2, rows_left):
global n, od
if (need1, need2, rows_left) in dp:
return dp[(need1, need2, rows_left)]
if rows_left == 1:
return 1
total = 0
if need1 >= 2:
total += rows_left*(rows_left-1)/2*count_rows(need1-2, need2, rows_left-1)
if need2 >=1 and need1 >= 1:
total += rows_left*(rows_left-1)/2*count_rows(need1, need2-1, rows_left-1)
if need2 >= 2:
total += rows_left*(rows_left-1)/2*count_rows(need1+2, need2-2, rows_left-1)
print(need1, need2, rows_left, total)
return total % od
#print(need1, need2, rows_left)
if need2*2 + need1 != 2*rows_left:
print(0)
else:
if rows_left == 0:
print(1)
print(count_rows(need1, need2, rows_left))
```
No
| 4,594 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An n Γ n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
Input
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
Output
Print the remainder after dividing the required value by number mod.
Examples
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
Note
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
Submitted Solution:
```
n, m, od = map(int, input().split())
ones_in_c = [0 for i in range(n)]
for i in range(m):
inp = input()
for j in range(n):
ones_in_c[j] = ones_in_c[j]+1 if inp[j] == '1' else ones_in_c[j]
need2 = ones_in_c.count(0)
need1 = ones_in_c.count(1)
rows_left = n-m
dp = {}
def count_rows(need1, need2, rows_left):
global n, od
if (need1, need2, rows_left) in dp:
return dp[(need1, need2, rows_left)]
if rows_left == 1:
return 1
total = 0
if need1 >= 2:
total += rows_left*(rows_left-1)/2*count_rows(need1-2, need2, rows_left-1)
if need2 >=1 and need1 >= 1:
total += rows_left*(rows_left-1)/2*count_rows(need1, need2-1, rows_left-1)
if need2 >= 2:
total += rows_left*(rows_left-1)/2*count_rows(need1+2, need2-2, rows_left-1)
#print(need1, need2, rows_left, total)
return total % od
#print(need1, need2, rows_left)
if need2*2 + need1 != 2*rows_left:
print(0)
else:
if rows_left == 0:
print(1)
print(int(count_rows(need1, need2, rows_left)))
```
No
| 4,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an element of the subtree rooted at ai's left child. Similarly in the case of right direction bi is an element of the subtree rooted at ai's right child.
Input
The first line of input contains two integers n and c. The next c lines contain 2 integers ai, bi (1 β€ ai, bi β€ n) and either "LEFT" or "RIGHT" denoting whether b is in the subtree rooted at ai's left child or in the subtree rooted at ai's right child.
The problem consists of multiple subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem D1 (9 points), the constraints 1 β€ n β€ 100, 1 β€ c β€ 50 will hold.
* In subproblem D2 (8 points), the constraints 1 β€ n β€ 1000000, 1 β€ c β€ 100000 will hold.
Output
Output will be on a single line.
Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as n space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices.
If there are no trees that satisfy the constraints, print "IMPOSSIBLE" (without quotes).
Examples
Input
3 2
1 2 LEFT
1 3 RIGHT
Output
2 1 3
Input
3 2
1 2 RIGHT
1 3 LEFT
Output
IMPOSSIBLE
Note
Consider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2, 1, 3).
Pre-order is the "root β left subtree β right subtree" order. In-order is the "left subtree β root β right subtree" order.
For other information regarding in-order and pre-order, see <http://en.wikipedia.org/wiki/Tree_traversal>.
Submitted Solution:
```
import sys
n, c = map(int, input().split())
COND = []
for i in range(c):
x = input().split()
if int(x[0]) >= int(x[1]):
print("IMPOSSIBLE")
sys.exit(0)
COND.append((int(x[0]), int(x[1]), x[2]))
V = [i + 1 for i in range(n)]
def dfs(curr, s):
for cond in COND:
if cond[0] == s:
s.add(cond[1])
dfs(cond[1])
def build(left_b, right_b):
if left_b == right_b:
return [left_b]
start = left_b
left_b += 1
left = set()
right = set()
for cond in COND:
if cond[0] == start:
if cond[2] == "LEFT":
left.add(cond[1])
dfs(cond[1], left)
else:
right.add(cond[1])
dfs(cond[1], right)
if len(left) > 0 and min(left) < left_b:
print("IMPOSSIBLE")
sys.exit(0)
if len(right) > 0 and max(right) > right_b:
print("IMPOSSIBLE")
sys.exit(0)
if left and right and max(left) >= min(right):
print("IMPOSSIBLE")
sys.exit(0)
mid = (left_b + right_b) // 2
if left and mid < max(left):
mid = max(left)
if right and mid > min(right) - 1:
mid = min(right) - 1
return build(left_b, mid) + [start] + build(mid + 1, right_b)
print(" ".join(map(str, build(1, n))))
```
No
| 4,596 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an element of the subtree rooted at ai's left child. Similarly in the case of right direction bi is an element of the subtree rooted at ai's right child.
Input
The first line of input contains two integers n and c. The next c lines contain 2 integers ai, bi (1 β€ ai, bi β€ n) and either "LEFT" or "RIGHT" denoting whether b is in the subtree rooted at ai's left child or in the subtree rooted at ai's right child.
The problem consists of multiple subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem D1 (9 points), the constraints 1 β€ n β€ 100, 1 β€ c β€ 50 will hold.
* In subproblem D2 (8 points), the constraints 1 β€ n β€ 1000000, 1 β€ c β€ 100000 will hold.
Output
Output will be on a single line.
Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as n space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices.
If there are no trees that satisfy the constraints, print "IMPOSSIBLE" (without quotes).
Examples
Input
3 2
1 2 LEFT
1 3 RIGHT
Output
2 1 3
Input
3 2
1 2 RIGHT
1 3 LEFT
Output
IMPOSSIBLE
Note
Consider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2, 1, 3).
Pre-order is the "root β left subtree β right subtree" order. In-order is the "left subtree β root β right subtree" order.
For other information regarding in-order and pre-order, see <http://en.wikipedia.org/wiki/Tree_traversal>.
Submitted Solution:
```
import sys
n, c = map(int, input().split())
COND = []
for i in range(c):
x = input().split()
if int(x[0]) >= int(x[1]):
print("IMPOSSIBLE")
sys.exit(0)
COND.append((int(x[0]), int(x[1]), x[2]))
V = [i + 1 for i in range(n)]
def dfs(curr, s):
for cond in COND:
if cond[0] == s:
s.add(cond[1])
dfs(cond[1])
def build(left_b, right_b):
if left_b == right_b:
return [left_b]
start = left_b
left_b += 1
left = set()
right = set()
for cond in COND:
if cond[0] == start:
if cond[2] == "LEFT":
left.add(cond[1])
dfs(cond[1], left)
else:
right.add(cond[1])
dfs(cond[1], right)
if len(left) > 0 and min(left) < left_b:
print("IMPOSSIBLE")
sys.exit(0)
if len(right) > 0 and max(right) > right_b:
print("IMPOSSIBLE")
sys.exit(0)
if left and right and max(left) >= min(right):
print("IMPOSSIBLE")
sys.exit(0)
if not left and not(right):
return [start] + [i for i in range(left_b, right_b + 1)]
if not left:
return [start] + build(left_b, right_b)
if not right:
return build(left_b, right_b) + [start]
mid = (left_b + right_b) // 2
if left and mid < max(left):
mid = max(left)
if right and mid > min(right) - 1:
mid = min(right) - 1
return build(left_b, mid) + [start] + build(mid + 1, right_b)
print(" ".join(map(str, build(1, n))))
```
No
| 4,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.
The teacher gave Andrew an array of n numbers a1, ..., an. After that he asked Andrew for each k from 1 to n - 1 to build a k-ary heap on the array and count the number of elements for which the property of the minimum-rooted heap is violated, i.e. the value of an element is less than the value of its parent.
Andrew looked up on the Wikipedia that a k-ary heap is a rooted tree with vertices in elements of the array. If the elements of the array are indexed from 1 to n, then the children of element v are elements with indices k(v - 1) + 2, ..., kv + 1 (if some of these elements lie outside the borders of the array, the corresponding children are absent). In any k-ary heap every element except for the first one has exactly one parent; for the element 1 the parent is absent (this element is the root of the heap). Denote p(v) as the number of the parent of the element with the number v. Let's say that for a non-root element v the property of the heap is violated if av < ap(v).
Help Andrew cope with the task!
Input
The first line contains a single integer n (2 β€ n β€ 2Β·105).
The second line contains n space-separated integers a1, ..., an ( - 109 β€ ai β€ 109).
Output
in a single line print n - 1 integers, separate the consecutive numbers with a single space β the number of elements for which the property of the k-ary heap is violated, for k = 1, 2, ..., n - 1.
Examples
Input
5
1 5 4 3 2
Output
3 2 1 0
Input
6
2 2 2 2 2 2
Output
0 0 0 0 0
Note
Pictures with the heaps for the first sample are given below; elements for which the property of the heap is violated are marked with red.
<image> <image> <image> <image>
In the second sample all elements are equal, so the property holds for all pairs.
Tags: brute force, data structures, math, sortings
Correct Solution:
```
import sys
def myargsort(a):
b = list(zip(a, range(0, len(a))))
b.sort()
r = [pr[1] for pr in b]
return r
fin = sys.stdin
n = int(fin.readline())
a = [int(number) for number in fin.readline().split()]
p = myargsort(a)
p.reverse()
j = 0
aib = [0] * (n + 1)
def ultb(x):
return -(x ^ (-x)) // 2
def add(p, a, aib, n):
while p <= n:
aib[p] += a
p += ultb(p)
def suma(p, aib):
r = 0
while p > 0:
r += aib[p]
p -= ultb(p)
return r
for i in range(0, n):
add(i + 1, 1, aib, n)
r = [0] * (n + 1)
for i in range(0, n):
if i > 0 and a[i - 1] > a[i]:
r[1] += 1
while j < n and a[p[j]] == a[p[i]]:
add(p[j] + 1, -1, aib, n)
j += 1
k = 2
while k < n and p[i] * k + 1 < n:
dr = min(n, p[i] * k + k + 1)
st = p[i] * k + 2
r[k] += suma(dr, aib) - suma(st - 1, aib)
k += 1
print(*r[1:n])
```
| 4,598 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two kittens, Max and Min, play with a pair of non-negative integers x and y. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, x and y became negative at the same time, and kitten Max tries to prevent him from doing so.
Each kitten has a set of pairs of integers available to it. Kitten Max has n pairs of non-negative integers (ai, bi) (1 β€ i β€ n), and kitten Min has m pairs of non-negative integers (cj, dj) (1 β€ j β€ m). As kitten Max makes a move, it can take any available pair (ai, bi) and add ai to x and bi to y, and kitten Min can take any available pair (cj, dj) and subtract cj from x and dj from y. Each kitten can use each pair multiple times during distinct moves.
Max moves first. Kitten Min is winning if at some moment both numbers a, b are negative simultaneously. Otherwise, the winner of the game is kitten Max. Determine which kitten wins if both of them play optimally.
Input
The first line contains two integers, n and m (1 β€ n, m β€ 100 000) β the number of pairs of numbers available to Max and Min, correspondingly.
The second line contains two integers x, y (1 β€ x, y β€ 109) β the initial values of numbers with which the kittens are playing.
Next n lines contain the pairs of numbers ai, bi (1 β€ ai, bi β€ 109) β the pairs available to Max.
The last m lines contain pairs of numbers cj, dj (1 β€ cj, dj β€ 109) β the pairs available to Min.
Output
Print Β«MaxΒ» (without the quotes), if kitten Max wins, or "Min" (without the quotes), if kitten Min wins.
Examples
Input
2 2
42 43
2 3
3 2
3 10
10 3
Output
Min
Input
1 1
1 1
3 4
1 1
Output
Max
Note
In the first test from the statement Min can respond to move (2, 3) by move (3, 10), and to move (3, 2) by move (10, 3). Thus, for each pair of Max and Min's moves the values of both numbers x and y will strictly decrease, ergo, Min will win sooner or later.
In the second sample test after each pair of Max and Min's moves both numbers x and y only increase, thus none of them will become negative.
Submitted Solution:
```
#encoding:utf-8
import math
strsRounds = input()
tmp = strsRounds.split(' ')
roundMax = int(tmp[0])
roundMin = int(tmp[1])
rounds = roundMax + roundMin
strsNums = input()
tmp = strsNums.split(' ')
baseNum1 = int(tmp[0])
baseNum2 = int(tmp[1])
baseDif = baseNum1 - baseNum2
strsListMax = []
strsListMin = []
xOperMax = 0
yOperMax = 0
xOperMin = 0
yOperMin = 0
for inputL in range(roundMax):
tmpstr = input()
tmpList = tmpstr.split(' ')
tmpList.append(int(tmpList[0])-int(tmpList[1]))
if xOperMax < int(tmpList[0]):
xOperMax = int(tmpList[0])
if yOperMax < int(tmpList[1]):
yOperMax = int(tmpList[1])
strsListMax.append(tmpList)
strsListMax.append(tmpList)
for inputL in range(roundMin):
tmpstr = input()
tmpList = tmpstr.split(' ')
tmpList.append(int(tmpList[0])-int(tmpList[1]))
if xOperMin < int(tmpList[0]):
xOperMin = int(tmpList[0])
if yOperMin < int(tmpList[1]):
yOperMin = int(tmpList[1])
strsListMin.append(tmpList)
if (xOperMax >= xOperMin) or (yOperMax >= yOperMin):
print ("Max")
else:
print ("Min")
```
No
| 4,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.