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 math
def get_first_max(tree, idx, l, r, L, R):
if r <= L or R <= l:
if l >= L and r <= R:
return tree[idx]
m = (l + r) // 2
return max(get_first_max(tree, idx * 2 + 1, l, m, L, R), get_first_max(tree, idx * 2 + 2, m, r, L, R))
num = input()
k = int(input())
n = len(num)
N = 2**math.ceil(math.log2(n))
M1 = 10 ** 7
M2 = 10 ** 6
tree = [-1] * (2 * N)
for i in range(n):
tree[N - 1 + i] = int(num[i]) * M1 + M2 - i
for i in range(N - 2, -1, -1):
tree[i] = max(tree[2 * i + 1], tree[2 * i + 2])
i = 0
ans = ""
for _ in range(n - k):
maximum = get_first_max(tree, 0, 0, N, i, i + k + 1)
val = maximum // M1
pos = M2 - maximum % M1
ans += str(val)
k -= pos - i
i = pos + 1
if k == 0:
ans += num[i:]
break
print(ans)
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 math
import sys
def get_first_max(tree, idx, l, r, L, R):
if r <= L or R <= l:
return -1
if l >= L and r <= R:
return tree[idx]
m = (l + r) // 2
return max(get_first_max(tree, idx * 2 + 1, l, m, L, R), get_first_max(tree, idx * 2 + 2, m, r, L, R))
num = input()
k = int(input())
n = len(num)
N = 2**math.ceil(math.log2(n))
M1 = 10 ** 7
M2 = 10 ** 6
tree = [-1] * (2 * N)
for i in range(n):
tree[N - 1 + i] = int(num[i]) * M1 + M2 - i
for i in range(N - 2, -1, -1):
tree[i] = max(tree[2 * i + 1], tree[2 * i + 2])
i = 0
ans = ""
for _ in range(n - k):
maximum = get_first_max(tree, 0, 0, N, i, i + k + 1)
val = maximum // M1
pos = M2 - maximum % M1
ans += str(val)
k -= pos - i
i = pos + 1
if k == 0:
ans += num[i:]
break
print(ans)