Smugglers
Time limit1sMemory limit128 MB
Find a cycle from gold back to gold that minimizes total conversion cost plus 50% of the cheapest metal's price along the cycle.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, Greedy, Sorting
- Solved
- No attempts yet
Problem
Byteotia is famous for its rich deposits of gold. For many years it sold that metal to a neighbouring kingdom, Bitland. Unfortunately, a growing budget deficit forced the king of Bitland to impose heavy tariffs on metals and minerals: any trader crossing the border must pay a customs duty of 50% of the value of the transported load.
Fortunately, Byteotian alchemists have found ways to turn one metal into another. The merchants' idea is to turn gold into some cheap metal, cross the border paying only a small tariff, and then turn it back into gold. However, the alchemists cannot turn an arbitrary metal directly into any other one, so obtaining a given metal from gold may require a chain of transformations that passes through a different metal at each stage. For every transformation they can perform, the alchemists fix a price for converting 1 kg of a metal A into a metal B, and they charge stiff fees.
Gold is metal number 1. We look for a sequence of metals such that:
- is gold (metal 1);
- for each the alchemists can obtain metal from metal ;
- the cost of performing the whole sequence of transformations on 1 kg of gold, plus the border duty, is as small as possible. Here the duty is 50% of the price of 1 kg of the cheapest metal among for .
Assume that the weight of the metal does not change during the alchemical processes.
Output the cost of performing the chosen sequence of transformations plus the duty paid at the border.
Input
The first line contains one positive integer , the number of distinct metals (). For , line contains a non-negative even integer , the price of 1 kg of the -th metal (). Gold is metal number 1. Line contains one non-negative integer , the number of transformations the alchemists can perform (). Each of the next lines contains three integers , , separated by single spaces: the alchemists can obtain metal from metal and charge bytealers to convert 1 kg of it (, ). Each ordered pair appears in the input at most once.
Output
Output a single integer: the cost of performing the transformations chosen by your program, plus the duty paid at the border.