This page is still under construction.

Parts of this page are still being built. What you see may change.

Floating Islands

Time limit8sMemory limit512 MB

Summary
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 nn islands, numbered 11 through nn. 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 ii has two parameters pip_i and did_i. At most did_i bridges can touch island ii. Building a bridge between island ii and island jj costs ∣pi−pj∣|p_i - p_j|. 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 6060. 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 nn (2≤n≤40002 \le n \le 4000), the number of islands. The next nn lines hold the parameters of the islands, where pip_i (1≤pi≤1091 \le p_i \le 10^9) and did_i (1≤di≤n1 \le d_i \le n) are the parameters of island ii.

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 −1-1 on one line.

Examples2

  1. Example 1

    Input
    4
    1 1
    8 2
    9 1
    14 2
    4
    181 4
    815 4
    634 4
    370 4
    4
    52 1
    40 1
    81 2
    73 1
    10
    330 1
    665 3
    260 1
    287 2
    196 3
    243 1
    815 1
    287 3
    330 1
    473 4
    0
    
    Expected output
    18
    634
    -1
    916
    
  2. Example 2

    Input
    2
    1 1
    1000000000 1
    2
    1000000000 2
    1 2
    0
    
    Expected output
    999999999
    999999999