Under construction

Still being built. Things may change

Train Scheduling

Time limit2sMemory limit1024 MB

Summary
Schedule N trains from two stations on one shared track so opposite-direction trains never overlap, minimizing the total delay past each train's earliest departure.
Level

Hard8 of 10

Topics
Sorting, Dynamic programming, Greedy
Solved
No attempts yet

Problem

Bessie has taken a new job as a train dispatcher. There are two stations, AA and BB. Because of budget limits, only one track connects them. If a train departs a station at time tt, it arrives at the other station at time t+Tt+T (1≤T≤10121\le T\le 10^{12}).

There are NN trains (1≤N≤50001\le N\le 5000) whose departure times must be scheduled. The iith train must leave station sis_i at time tit_i or later (si∈{A,B}s_i\in \{A, B\}, 0≤ti≤10120\le t_i\le 10^{12}).

Trains going in opposite directions may not be on the track at the same time, because they would crash. Many trains may travel in the same direction at the same time. Assume trains have negligible size.

Input

The first line contains NN and TT. Each of the next NN lines contains the station sis_i and the time tit_i for the iith train.

Output

Print the minimum possible total delay over all valid schedules. If train ii departs at time ai≥tia_i\ge t_i, the total delay is ∑i=1N(ai−ti)\sum_{i=1}^N(a_i-t_i).

Examples4

  1. Example 1

    Input
    1 95
    B 63
    
    Expected output
    0
    
  2. Example 2

    Input
    4 1
    B 3
    B 2
    A 1
    A 3
    
    Expected output
    1
    
  3. Example 3

    Input
    4 10
    A 1
    B 2
    A 3
    A 21
    
    Expected output
    13
    
  4. Example 4

    Input
    8 125000000000
    B 17108575619
    B 57117098303
    A 42515717584
    B 26473500855
    A 108514697534
    B 110763448122
    B 117731666682
    A 29117227954
    
    Expected output
    548047356974