Imperial roads
Time limit1sMemory limit1024 MB
For each road, report the cost of a minimum spanning tree forced to include that road. Queries are offline and non-repeating.
- Level
Hard8 of 10
- Topics
- Minimum spanning tree, Union-find, Graph
- Solved
- No attempts yet
Problem
The roads of Cubiconia are in bad shape after years without maintenance. Each road connects two different cities and and can be traveled in both directions. There is at most one road between a pair of cities, and the existing roads already let anyone travel between any pair of cities. The new emperor raised the taxes again and promised to repair some of the roads, so that Cubiconians can travel between any pair of cities using only repaired roads.
The Department of Public Works has computed the repair cost of every road. It now wants the cheapest set of roads that keeps the emperor's promise. That is not easy, because the emperor wants one particular road to be in the repaired set and has not decided which one. It could be the road between the city of his castle and the city of his daughter's residence, or the road between the city of his summer palace and the only city by the sea. The engineers expect the decision to take a while, so they want the answer for every candidate in advance.
Given the roads of Cubiconia with their repair costs, write a program that answers a set of queries. Each query names one specific road that must be repaired. For that query, report the minimum total repair cost of a set of roads that contains the named road and lets Cubiconians travel between any pair of cities using only repaired roads.
Input
The first line contains two integers and , the number of cities and the number of roads in Cubiconia (, ). Cities are identified by distinct integers from to .
Each of the next lines describes a road with three integers , and (, ), meaning that there is a road between cities and and that repairing it costs . There is at most one road between a pair of cities, and the given roads let anyone travel between any pair of cities.
The next line contains an integer , the number of queries (). Each of the next lines describes a query with two integers and (), meaning that the road between cities and must be repaired. That road is one of the roads given in the input. No query is repeated.
Output
Output lines. Line contains one integer, the answer to query : the minimum total repair cost of a set of roads that contains the road named by the query and lets Cubiconians travel between any pair of cities using only repaired roads.