DMOPC '18 Contest 5 P5 - A Hat Problem

View as PDF

Submit solution


Points: 20 (partial)
Time limit: 2.5s
Memory limit: 256M

Author:
Problem types

N people have gathered to trade their hats! They have numbered themselves from 1 to N and lined up in this order. The ith person initially has a hat with value vi but would like a hat with value wi. After some discussion, the hat fans decided on the following method of hat trading: The first person in line can either leave with the hat currently on their head, or they may switch hats with the person directly behind them (if there is anyone) and then leave. This process happens N times until everyone has left.

At the end of this process, say person i left wearing a hat valued at hi. The overall unhappiness is then defined as i=1N|hiwi|. Can you help these traders minimize their overall unhappiness?

Constraints

1vi,wi1000000

Subtask 1 [20%]

1N20

Subtask 2 [30%]

1N2000

Subtask 3 [50%]

1N200000

Input Specification

The first line contains a single integer N.
The next N lines each contain two space-separated integers, vi and wi.

Output Specification

Output a single space-separated integer, the minimum possible unhappiness.

Sample Input

Copy
4
15 4
3 18
10 3
8 2

Sample Output

Copy
17

Explanation for Sample

The first person trades his hat with the second person in line and leaves with a hat of value 3. The next three people leave without any more trades. The overall unhappiness is |34|+|1518|+|103|+|82|=17 which is the minimum.


Comments

There are no comments at the moment.