Floating Islands
Time limit8sMemory limit512 MB
Find the cheapest connected bridge network where each bridge costs the position difference and each island has a degree limit, or report -1 when impossible.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Minimum spanning tree, Sorting
- Solved
- No attempts yet
Problem
You have just arrived in a small country. A huge hurricane swept across it a few days ago.
The country is made up of islands, numbered through . Many bridges connected the islands, but the flood washed all of them away. The islanders need new bridges to travel among the islands again.
The problem is cost. The country is not wealthy, so the government has to keep spending down. They asked you, a great programmer, to compute the minimum cost of rebuilding the bridges.
Each bridge connects two islands and can be crossed in both directions. Island has two parameters and . At most bridges can touch island . Building a bridge between island and island costs . People have to be able to travel between every pair of islands over a sequence of bridges, and the given limits sometimes make that impossible.
Input
The input is a sequence of datasets. The number of datasets is at most . Each dataset has the following format.
n
p_1 d_1
p_2 d_2
...
p_n d_n
Every value in the input is an integer. The first line holds (), the number of islands. The next lines hold the parameters of the islands, where () and () are the parameters of island .
A line with a single zero marks the end of the input.
Output
For each dataset, print the minimum cost on one line if the bridges can be rebuilt within the given limits. Otherwise print on one line.