Junseo the Librarian King
Time limit2sMemory limit512 MB
Given book numbers and weights, move the lightest total weight of books so the numbers end up in non-decreasing order.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Sorting, Greedy, Implementation
- Solved
- No attempts yet
Problem
Junseo wants to be the best librarian in the world. Library after library turned him down, but he passed the librarian hiring round at ANSI (Ajou Nerd Standards Institution), which owns the best library in the world.
Every new ANSI librarian goes through a training course that checks the basics of the job. The hardest part of it is reshelving. Books on a shelf must sit in non-decreasing order of book number so that visitors can find them, but Yongjae D. Ash, called the nerd king, sits in the library all day and pushes every book he has read into whatever slot he likes. It is a nerds' library, so the books are heavy too, and Junseo now has sore muscles.
Find the smallest labor needed to sort the shelf. Labor is the total force spent moving books, and moving one book takes force equal to its weight no matter how far it travels. The slot where a pulled book goes back always has enough room, and the job is finished as soon as the book numbers are in order.
Input
The first line contains the number of books () that Junseo has to sort.
The second line contains the book numbers in their current shelf order.
The third line contains the weights in the same order.
Every book number is a real number greater than and less than , and every weight is an integer from to .
Output
Print the minimum labor needed to sort the shelf on one line.
Hint
In the first example, moving the third book to the front costs , which is the minimum.
In the second example, moving the first, third, fifth and eighth books into their right slots costs , which is the minimum.