Vials
Time limit3sMemory limit256 MB
Pour vials in the given order, react each mixed pair to exhaustion in priority order, and total the sediment formed.
- Level
Hard8 of 10
- Topics
- Union-find, Simulation, Greedy, Graph
- Solved
- No attempts yet
Problem
Bajtazar is a chemist. He is running an experiment that produces remedy X, a mixture that solves every problem of humankind.
Bajtazar has vials numbered through , and each vial holds a different liquid substance. Vial holds a whole number of grams of substance . Producing remedy X takes a sequence of steps. One step pours the entire contents of one vial into another vial. Assume the vials are large enough and that no drop is spilled while pouring. The vial that was poured out goes on a shelf and is not used again during the experiment.
Some pairs of substances react with each other and form a compound that settles as sediment. In each such reaction gram of the first substance combines with gram of the second, and grams of sediment appear. The reaction runs until one of its substrates is used up. The sediment reacts with nothing and stays on the wall of the vial where it formed until the experiment ends. Some reactions run faster than others. If several substances end up in one solution at the same time, the reactions between pairs of substances happen in a fixed order that Bajtazar knows. After each step Bajtazar waits until the substances in the destination vial have finished reacting, and only then performs the next step.
Bajtazar wonders whether his sequence of steps is optimal. He wants to know how much of the substrates is wasted once every step is done. Find the total number of grams of sediment.
Input
The first line contains three integers , , (, ): the number of vials (which is also the number of distinct substances), the number of steps in the experiment, and the number of substance pairs that react and form sediment.
The second line contains integers (), where is the initial number of grams of substance in vial .
Each of the next lines describes one step, in order. The -th of these lines contains two integers , (, ), meaning that step pours the contents of vial into vial . If a vial is poured out in some step, it does not appear in any later step.
Each of the next lines describes one pair of substances that forms sediment. The -th of these lines contains two integers , (, ), meaning that if substances and are in one vial at the same time, they react and sediment forms. The pairs are listed from the highest reaction priority to the lowest. If a vial holds two or more reacting pairs, the pair listed earlier in the input starts reacting first and finishes completely before the next pair starts. Ignoring the order inside a pair, the same pair never appears twice.
Output
Print one integer, the total number of grams of sediment after the whole sequence of steps.