Librarian's Work

Time limit5sMemory limit512 MB

Summary
Given a shuffled permutation with book weights, restore the original order using two adjacent-rotation-like moves and minimize total labor cost.
Level

Hard8 of 10

Topics
Greedy, Dynamic programming, Sorting, Implementation
Solved
No attempts yet

Problem

The Japanese Animal Girl Library (JAG Library) is famous for a long bookshelf. It contains NN books numbered from 11 to NN from left to right. The weight of the ii-th book is wiw_i.

One day, the naughty fox Jiro shuffled the order of the books on the shelf! The order has become the permutation b1,…,bNb_1, \ldots, b_N from left to right. The fox Hanako, a librarian of the JAG Library, must restore the original order. She can rearrange a permutation of books p1,⋯ ,pNp_1, \cdots, p_N by performing either operation A or operation B described below, with arbitrary two integers ll and rr such that 1≤l<r≤N1 \le l < r \le N holds.

Operation A:

  • A-1. Remove plp_l from the shelf.
  • A-2. Shift the books between pl+1p_{l+1} and prp_r to the left.
  • A-3. Insert plp_l to the right of prp_r.

Operation B:

  • B-1. Remove prp_r from the shelf.
  • B-2. Shift the books between plp_l and pr−1p_{r-1} to the right.
  • B-3. Insert prp_r to the left of plp_l.

This picture shows the orders of the books before and after applying operations A and B for p=(3,1,4,5,2,6)p=(3,1,4,5,2,6), l=2l=2, r=5r=5.

Since the books are heavy, operation A needs ∑i=l+1rwpi+C×(r−l)×wpl\sum_{i=l+1}^{r} w_{p_i} + C \times (r-l) \times w_{p_l} units of labor and operation B needs ∑i=lr−1wpi+C×(r−l)×wpr\sum_{i=l}^{r-1} w_{p_i} + C \times (r-l) \times w_{p_r} units of labor, where CC is a given positive integer constant.

Hanako must restore the initial order from b1,⋯ ,bNb_1, \cdots, b_N by performing these operations repeatedly. Find the minimum sum of labor needed to achieve this.

Input

The input consists of a single test case formatted as follows.

$N \ C$
$b_1 \ w_{b_1}$
$\vdots$
$b_N \ w_{b_N}$

The first line consists of two integers NN and CC (1≤N≤105,1≤C≤100)(1 \le N \le 10^5, 1 \le C \le 100). The (i+1)(i+1)-th line consists of two integers bib_i and wbiw_{b_i} (1≤bi≤N,1≤wbi≤105)(1 \le b_i \le N, 1 \le w_{b_i} \le 10^5). The sequence (b1,…,bN)(b_1, \ldots, b_N) is a permutation of (1,…,N)(1, \ldots, N).

Output

Print the minimum sum of labor in one line.

Examples3

  1. Example 1

    Input
    3 2
    2 3
    3 4
    1 2
    
    Expected output
    15
    
  2. Example 2

    Input
    3 2
    1 2
    2 3
    3 3
    
    Expected output
    0
    
  3. Example 3

    Input
    10 5
    8 3
    10 6
    5 8
    2 7
    7 6
    1 9
    9 3
    6 2
    4 5
    3 5
    
    Expected output
    824