Library shelf tidying

No attempts yetTime limit1sMemory limit64 MB

Problem

Librarian Jurica works in a library with NN shelves, and each shelf holds up to MM 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 NN and MM (1N10001 \le N \le 1000, 1M10001 \le M \le 1000).

Each of the next NN lines contains MM integers, and the ii-th line describes the current state of the ii-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 KK is the total number of books on the shelves, the books carry the distinct numbers 1 to KK.

The next NN 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.