Library shelf tidying
Time limit1sMemory limit64 MB
Given current and target shelf layouts, find the minimum number of books to lift when sliding a book into an empty spot on the same shelf costs nothing.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Binary search
- Solved
- No attempts yet
Problem
Librarian Jurica works in a library with shelves, and each shelf holds up to books. Jurica is taking inventory and wants to put every misplaced book back where it belongs. He moves a book in one of two ways.
- He slides a book one place to the left or to the right on its own shelf. The place he slides it into has to be empty.
- He lifts one book and puts it on an empty place of the same shelf or of any other shelf.
Jurica cannot slide a book while he holds one in his hands, and he never holds more than one book at a time.
Jurica's back has hurt ever since he carried the whole printed edition of Wikipedia from the first floor to the second, so he wants to put every book in place with as few lifts as he can. Find the smallest number of lifts he needs.
Input
The first line contains the integers and (, ).
Each of the next lines contains integers, and the -th line describes the current state of the -th shelf. A 0 marks an empty place, and a number other than 0 means the book with that number sits in that place. If is the total number of books on the shelves, the books carry the distinct numbers 1 to .
The next lines describe the wanted state of the shelves in the same format. The same books appear in the initial state and in the wanted state.
Output
Print the smallest number of lifts on one line. Print -1 if the books cannot be arranged in the described way.
Hint
The first example goes like this. Jurica slides book 1 one place to the right. He lifts book 2 and puts it on the first place of the first shelf. He lifts book 5 and puts it on the fourth place of the second shelf.