def minimum_railroad_cars(t, cases): for i in range(t): n = cases[i][0] d = cases[i][1] c = cases[i][2] # Initialize available cars at each station to 0 available_cars = [0] * n # Initialize list of stations in increasing order of the number of railroad cars needed stations = list(range(n)) stations.sort(key=lambda x: d[x]) # Perform shipments for i in stations: needed_cars = c[i] available_cars_i = available_cars[i] available_cars_di = available_cars[d[i]] # Check if there are enough available cars to perform the shipment if available_cars_i < needed_cars: # If not, the problem is impossible print(f"Case #{i+1}: -1") break # Perform shipment and update available cars shipped_cars = min(needed_cars, available_cars_i) available_cars[i] -= shipped_cars available_cars[d[i]] += shipped_cars # Make sure station i has at least c[i] available cars after the shipment available_cars_i = available_cars[i] if available_cars_i < c[i]: available_cars[d[i]] += c[i] - available_cars_i available_cars[i] = c[i] else: # All shipments were performed successfully, output the minimum number of railroad cars needed print(f"Case #{i+1}: {sum(available_cars)}")