import sys
A = int(input())
B = int(input())
C = int(input())
D = int(input())
K = int(input())
def check(x, y):
if abs(x) > K or abs(y) > K:
return 0
y += A
if y >= K:
return A - (y - K)
x += B
if x >= K:
return A + B - (x - K)
y -= C
if y <= -K:
return A + B + C - (-y - K)
x -= D
if x <= -K:
return A + B + C + D - (-x - K)
return -1
if check(0, 0) != -1:
print(check(0, 0))
sys.exit(0)
x = B - D
y = A - C
left = 0
right = 10 ** 9
while right - left > 1:
mid = (left + right) // 2
if check(x * mid, y * mid) == -1:
left = mid
else:
right = mid
print(right * (A + B + C + D) + check(x * right, y * right))
Объяснение:
import sys
A = int(input())
B = int(input())
C = int(input())
D = int(input())
K = int(input())
def check(x, y):
if abs(x) > K or abs(y) > K:
return 0
y += A
if y >= K:
return A - (y - K)
x += B
if x >= K:
return A + B - (x - K)
y -= C
if y <= -K:
return A + B + C - (-y - K)
x -= D
if x <= -K:
return A + B + C + D - (-x - K)
return -1
if check(0, 0) != -1:
print(check(0, 0))
sys.exit(0)
x = B - D
y = A - C
left = 0
right = 10 ** 9
while right - left > 1:
mid = (left + right) // 2
if check(x * mid, y * mid) == -1:
left = mid
else:
right = mid
print(right * (A + B + C + D) + check(x * right, y * right))
Объяснение: