Under construction

Still being built. Things may change

Events Are Approaching (Hard)

Time limit4sMemory limit1024 MB

Summary
Given N timed events that forbid positions strictly between A and B at each time T, find the minimum total distance Minjeong moves to dodge them all, or -1 if impossible.
Level

Hard8 of 10

Topics
Dynamic programming, Intervals, Sorting
Solved
No attempts yet

Problem

Minjeong is currently at the origin (position 0) of a number line. At every moment, Minjeong can move left or right along the number line at a speed of 1 per second. Of course, Minjeong can also stay still.

Minjeong knows that the following event will occur NN times.

  • If Minjeong is at a position strictly greater than AA and strictly less than BB after TT seconds, Minjeong gets hit by Karina's body bang.

Positions AA and BB are safe.

Minjeong wants to move so as to avoid Karina's body bang. Determine whether Minjeong can avoid it by moving, and if so, minimize the total distance moved.

Input

The first line contains the number of events NN.

Each of the next NN lines contains TT, AA, and BB for one event, separated by spaces.

Output

If Minjeong cannot avoid Karina's body bang, print -1.

If Minjeong can avoid it, print the minimum distance Minjeong must move.

Constraints

  • All given numbers are integers.
  • 1≤N≤100 0001 \le N \le 100\,000
  • 1≤T≤1 000 000 0001 \le T \le 1\,000\,000\,000
  • −1 000 000 000≤A<B≤1 000 000 000-1\,000\,000\,000 \le A < B \le 1\,000\,000\,000
  • The TT of each event is distinct.

Examples3

  1. Example 1

    Input
    3
    10 -3 7
    20 -8 2
    25 3 9
    
    Expected output
    8
    
  2. Example 2

    Input
    3
    3 -3 7
    7 -8 2
    8 3 9
    
    Expected output
    -1
    
  3. Example 3

    Input
    10
    37 -8 16
    38 -4 16
    12 -42 -31
    24 -9 11
    16 -32 -14
    26 1 18
    11 -43 -40
    18 -17 2
    47 28 35
    33 -50 -49
    
    Expected output
    18