Oland must not fall
InterviewTime limit2sMemory limit512 MB
Given hospital supplies, demands, and an undirected tunnel graph with unit edge costs, find the minimum total cost to balance every hospital, or -1 if impossible.
- Level
Medium6 of 10
- Topics
- Graph, BFS, Greedy, Implementation
- Solved
- No attempts yet
Problem
A month has passed since the sixth army of the evil Miniophers invaded Olandica. Their troops are spread across Oland, a strategic city in western Olandica, and civilian casualties are heavy. The Olanders still hold a few hospitals, but they are short of Unophine, the drug that treats the damage caused by a biological weapon the Miniophers use. In response the Olanders dug a number of tunnels between hospitals. A pack of Unophine can be carried from one hospital to another whenever a tunnel joins them. The tunnels are narrow, so only one pack passes at a time, but the same tunnel can be used again as many times as needed.
Three times a day every hospital reports to the operations HQ how many packs it stores and how many packs it needs. HQ then builds a distribution plan that leaves every hospital holding exactly the number of packs it needs. The cost of a plan counts each pack once for every tunnel it crosses. A pack that crosses two tunnels costs .
For example, suppose hospitals A, B, and C store , , and packs, with a tunnel between A and B and a tunnel between B and C. If they need , , and packs, moving one pack from B to A and two packs from C to B works. That plan costs .
Given the tunnels and each hospital's storage and need, find the minimum cost of a distribution plan that leaves every hospital holding exactly what it needs.
Input
The first line contains the number of test cases ().
The first line of each test case contains the number of hospitals and the number of tunnels (). Hospitals are numbered from to .
Each of the next lines contains two integers and , the number of packs hospital stores and the number of packs it needs ().
Each of the next lines contains two integers and , meaning that a tunnel joins hospital and hospital (). Several tunnels may join the same pair of hospitals, and may equal .
Output
For each test case, print the minimum cost of a distribution plan on one line. If no plan leaves every hospital holding exactly what it needs, print .