This page is still under construction.

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

Trapped in the Haybales

Time limit1sMemory limit256 MB

Summary
The solver sorts bales by position, expands each gap while a neighbor is smaller than the open width, and sums the widths that never reach an end.
Level

Medium6 of 10

Topics
Two pointers, Sorting, Greedy
Solved
No attempts yet

Problem

Farmer John received NN large hay bales (1≤N≤40001 \le N \le 4000) and put them at various points along the road that leads to his barn. He forgot that Bessie the cow was grazing on that road, and she may now be trapped between the bales.

The road is a straight line. Bale jj has size SjS_j and position PjP_j, and all positions are distinct.

Bessie starts at some point where there is no bale and moves freely along the road. She can walk right up to the position of a bale, but she cannot pass through it. If she runs in one direction for a distance of DD, she builds up enough speed to smash one bale of size strictly less than DD and remove it for good. Removing a bale opens up more room to run, so she may then smash further bales.

Bessie escapes if she smashes either the leftmost bale or the rightmost bale. A start to the left of the leftmost bale, or to the right of the rightmost bale, always escapes, because she can run as far as she wants.

Compute the total length of road made up of the starting points from which Bessie cannot escape. Starting positions are real numbers. For example, if she cannot escape when she starts between bales at positions 11 and 55, that stretch has length 44.

Input

The first line contains NN. Each of the next NN lines contains the size and the position of one bale, separated by a space. Both values are integers between 11 and 10910^9, and the positions are distinct.

Output

Print a single integer, the total length of road from which Bessie cannot escape.

Examples5

  1. Example 1

    Input
    5
    8 1
    1 4
    8 8
    7 15
    4 20
    
    Expected output
    14
    
  2. Example 2

    Input
    1
    1000000000 1000000000
    
    Expected output
    0
    
  3. Example 3

    Input
    2
    1 1
    1 5
    
    Expected output
    0
    
  4. Example 4

    Input
    2
    10 1
    10 5
    
    Expected output
    4
    
  5. Example 5

    Input
    6
    2 10
    1000 1
    5 20
    1 2
    3 4
    100 9
    
    Expected output
    9