Librarian's Work
Time limit5sMemory limit512 MB
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 books numbered from to from left to right. The weight of the -th book is .
One day, the naughty fox Jiro shuffled the order of the books on the shelf! The order has become the permutation 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 by performing either operation A or operation B described below, with arbitrary two integers and such that holds.
Operation A:
- A-1. Remove from the shelf.
- A-2. Shift the books between and to the left.
- A-3. Insert to the right of .
Operation B:
- B-1. Remove from the shelf.
- B-2. Shift the books between and to the right.
- B-3. Insert to the left of .
This picture shows the orders of the books before and after applying operations A and B for , , .

Since the books are heavy, operation A needs units of labor and operation B needs units of labor, where is a given positive integer constant.
Hanako must restore the initial order from 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 and . The -th line consists of two integers and . The sequence is a permutation of .
Output
Print the minimum sum of labor in one line.