This page is still under construction.

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

Paper Rolls

Interview

Time limit1sMemory limit128 MB

Summary
Set every roll to one shared unrolled length within each total length using the fewest 1-cm moves.
Level

Medium5 of 10

Topics
Sorting, Math
Solved
No attempts yet

Problem

There are nn toilet paper rolls in a bathroom. The ii-th roll has a total length did_i and a currently unrolled length rir_i, and the unrolled length can never exceed the total length (that is, 0≤ri≤di0 \le r_i \le d_i).

In one move you may roll up or unroll exactly 1 cm of any single roll; in other words, one move increases or decreases some rir_i by 11, and 0≤ri≤di0 \le r_i \le d_i must still hold afterwards. Determine the minimum number of moves needed to make every roll have the same unrolled length.

Input

The first line contains the number of rolls nn (1≤n≤1061 \le n \le 10^6). Each of the next nn lines describes one roll with two integers did_i and rir_i, the total length and the unrolled length of the ii-th roll (0≤ri≤di≤1090 \le r_i \le d_i \le 10^9).

Output

Print a single integer: the minimum number of moves needed to make the unrolled lengths of all rolls equal.

Examples2

  1. Example 1

    Input
    3
    50 10
    40 20
    30 30
    
    Expected output
    20
    
  2. Example 2

    Input
    1
    10 5
    
    Expected output
    0