To solve this problem efficiently, we can follow these steps:
-
Match existing horses to win as many races as possible:
- Small a can rearrange his horses, and he knows the sequence of small b's horses.
- We sort small a's existing horse abilities in descending order and small b's horses in descending order.
- We match each of small a's horses to small b's horses where small a's horse has a higher ability.
- The number of wins we get from existing horses is
w1.
-
Determine the minimum number of additional wins needed:
- Calculate the minimum number of wins needed to win the game, which is
W = n // 2 + 1.
- Compute the additional wins required from purchased horses:
w2 = W - w1.
-
Purchase horses to secure the required additional wins:
- Consider the unassigned positions (the positions not yet assigned to existing horses).
- For each unassigned position, the minimum ability required to guarantee a win is
(b_i + 1) at a cost of (b_i + 1) coins.
- Sort the unassigned positions based on
b_i in ascending order.
- Select the first
w2 positions to purchase horses that guarantee wins.
- The total cost for these horses is the sum of
(b_i + 1) for these positions.
-
Purchase remaining horses with minimum possible cost:
- For the remaining positions, purchase horses with the minimum ability of
1 at a cost of 1 coin each.
-
Calculate the total cost:
- The total minimum cost is the sum of:
- The cost to purchase the horses that guarantee the required additional wins.
- The cost to purchase the remaining horses with minimum ability.
-
Check if winning is possible:
- If
w1 + (n - m) < W, it is impossible to win, output -1.
Below is the Python code implementing the above algorithm:
n = int(input())
b_list = list(map(int, input().split()))
m = int(input())
a_list = list(map(int, input().split()))
from collections import deque
n_total = n
b_list_with_pos = list(enumerate(b_list))
m_existing = m
a_existing = a_list
# Step 1: Match existing horses to win as many races as possible
a_existing_sorted = sorted(a_existing, reverse=True)
b_list_with_pos_sorted = sorted(b_list_with_pos, key=lambda x: -x[1]) # descending
positions_assigned = set()
w1 = 0 # Number of wins with existing horses
j = 0 # pointer for b_list_with_pos_sorted
for a in a_existing_sorted:
while j < n and b_list_with_pos_sorted[j][1] >= a:
j += 1
if j == n:
break
else:
pos = b_list_with_pos_sorted[j][0]
positions_assigned.add(pos)
w1 +=1
j +=1
W = n //2 +1
if w1 + (n - m) < W:
print(-1)
else:
w2 = max(0, W - w1)
# Get unassigned positions and their b_i
unassigned_positions = []
for i in range(n):
if i not in positions_assigned:
unassigned_positions.append(b_list[i])
unassigned_positions.sort()
# Cost for purchasing horses to guarantee w2 additional wins
total_cost = sum(b_i +1 for b_i in unassigned_positions[:w2])
# Cost for purchasing remaining horses with minimal ability
total_cost += (n - m - w2) * 1
print(total_cost)