#P7194. Minimum Toll Cost

    ID: 20398 Type: Default 1000ms 256MiB

Minimum Toll Cost

Minimum Toll Cost

Luka has n trucks traveling on a highway. The highway features many entry and exit ramps; the same ramp number denotes the same physical location. When a truck enters the highway at ramp s, the driver receives a ticket showing the entry number s. When the truck exits at ramp t (s and t are different), the toll charged is \( |t-s| \).

However, the drivers are allowed to exchange their entry tickets with one another (even when their journey intervals do not overlap), subject to the restriction that an exchange cannot be performed at a ramp where a truck either enters or exits (i.e. one cannot swap a ticket at a location where a truck boards or leaves the highway).

This means that effectively the drivers can reassign the entry numbers among themselves arbitrarily. In order to minimize the total toll fee, we want to reassign tickets such that the sum of tolls, which is given by

[ \text{Total Cost} = \sum_{i=1}^{n} |t_i - s_i|, ]

is minimized. It is well known that for a set of entry numbers \(\{s_i\}\) and exit numbers \(\{t_i\}\), the minimum possible total sum of absolute differences is obtained by sorting both lists in non-decreasing order and pairing the smallest entry with the smallest exit, the second smallest entry with the second smallest exit, and so on.

Given the information for each truck, calculate the minimum total toll that Luka has to pay.

inputFormat

The first line contains a single integer n (the number of trucks). Each of the next n lines contains two space-separated integers s and t (the entry ramp number and the exit ramp number respectively). It is guaranteed that s and t are different.

outputFormat

Output a single integer: the minimum total toll cost that can be achieved by optimal exchanges of the entry tickets.

sample

3
1 6
2 5
3 7
12