Cheap Deliveries
Time limit2sMemory limit512 MB
Given a weighted undirected graph and k up to 18 delivery pairs, find the order of deliveries that minimizes total travel distance, or report -1 if some delivery is unreachable.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, Dynamic programming, Bit manipulation
- Solved
- No attempts yet
Problem
Abu runs a delivery service that carries items from one city to another. One day Abu receives items to deliver. Each item must be carried from its start city to its destination city, and only one item can be carried at a time. The delivery order is free, as long as every item is delivered. Abu starts in the start city of some item, delivers it to its destination city, then moves to the start city of the next item and continues until no item remains.
Every road is bidirectional, and two cities may be connected by more than one road. Abu may use any road as many times as needed.
Given the list of cities, the roads between them with their lengths, and the list of deliveries, determine the minimum total travel distance needed to finish all deliveries in the most efficient order.
Input
The first line contains three integers , and : the number of cities, the number of roads and the number of items (, ).
Each of the next lines contains three integers , and (, ), meaning there is a road of length between city and city .
Each of the next lines contains two integers and (), meaning item must be delivered from city to city .
Output
Print a single integer: the minimum total travel distance when all items are delivered in the optimal order, or if it is impossible to deliver all items.
Hint
In the first case, starting from city and delivering the third item to city , then moving to city and delivering the second and first items in order, gives a total travel distance of , which is optimal.
In the second case, cities , and are disconnected from cities and , so it is impossible to deliver all items.