def simulate_shipments(n, departures, cars_needed, initial_cars): # Initialize number of cars available at each station to cars_needed available_cars = cars_needed.copy() # Initialize number of cars sent from each station to 0 sent_cars = [0] * n # Iterate over stations in increasing order of departure times for i in range(n): # Check if station i has enough cars available to make its shipment if available_cars[i] >= cars_needed[i]: # Station i can make its shipment using its own cars available_cars[i] -= cars_needed[i] available_cars[departures[i]-1] += cars_needed[i] sent_cars[i] = cars_needed[i] else: # Station i needs additional cars to make its shipment deficit = cars_needed[i] - available_cars[i] available_cars[i] = 0 available_cars[departures[i]-1] += deficit sent_cars[i] = available_cars[i] available_cars[i] = 0 # Return True if all shipments can be performed, False otherwise return all(sent_cars[i] >= cars_needed[i] for i in range(n)) def find_minimum_cars(n, departures, cars_needed): # Initialize search range to [0, sum(Ci)] lo, hi = 0, sum(cars_needed) # Binary search for minimum number of cars needed while lo < hi: mid = (lo + hi) // 2 if simulate_shipments(n, departures, cars_needed, [mid] * n): hi = mid else: lo = mid + 1 # Return the minimum number of cars needed return lo # Read input t = int(input()) for i in range(1, t+1): n = int(input()) departures = list(map(int, input().split())) cars_needed = list(map(int, input().split())) # Find minimum number of cars needed for initial supplies min_cars = find_minimum_cars(n, departures, cars_needed) # Print output print("Case #{}: {}".format(i, min_cars))