Time Limit: 5 sec / Memory Limit: 512 MB
Problem Statement
Japanese Animal Girl Library (JAG Library) is famous for a long bookshelf. It contains N books numbered from 1 to N from left to right. The weight of the i-th book is wi.
One day, naughty Fox Jiro shuffled the order of the books on the shelf! The order has become a permutation b1,…,bN from left to right. Fox Hanako, a librarian of JAG Library, must restore the original order. She can rearrange a permutation of books p1,⋯,pN by performing either operation A or operation B described below, with arbitrary two integers l and r such that 1≤l<r≤N holds.
Operation A:
- A-1. Remove pl from the shelf.
- A-2. Shift books between pl+1 and pr to left.
- A-3. Insert pl into the right of pr.
Operation B:
- B-1. Remove pr from the shelf.
- B-2. Shift books between pl and pr−1 to right.
- B-3. Insert pr into the left of pl.
This picture illustrates the orders of the books before and after applying operation A and B for p=(3,1,4,5,2,6), l=2, r=5.
Since the books are heavy, operation A needs ∑ri=l+1wpi+C×(r−l)×wpl units of labor and operation B needs ∑r−1i=lwpi+C×(r−l)×wpr units of labor, where C is a given constant positive integer.
Hanako must restore the initial order from b1,⋯,bN by performing these operations repeatedly. Find the minimum sum of labor to achieve it.
Input
The input consists of a single test case formatted as follows.
N C b1 wb1 ⋮ bN wbN
The first line conists of two integers N and C (1≤N≤105,1≤C≤100). The (i+1)-th line consists of two integers bi and wbi (1≤bi≤N,1≤wbi≤105). The sequence (b1,…,bN) is a permutation of (1,…,N).
Output
Print the minimum sum of labor in one line.
Sample Input 1Copy
3 2 2 3 3 4 1 2
Output for Sample Input 1Copy
15
Performing operation B with l=1,r=3, i.e. removing book 1 then inserting it into the left of book 2 is an optimal solution. It costs (3+4)+2×2×2=15 units of labor.
Sample Input 2Copy
3 2 1 2 2 3 3 3
Output for Sample Input 2Copy
0
Sample Input 3Copy
10 5 8 3 10 6 5 8 2 7 7 6 1 9 9 3 6 2 4 5 3 5
Output for Sample Input 3Copy
824