Bookshelf Sorting
Time limit2sMemory limit512 MB
Given a permutation, repeatedly answer the minimum number of take-and-insert-at-ends moves to sort it, after each of q swaps of two positions.
- Level
Hard8 of 10
- Topics
- Array, Dynamic programming, Segment tree, Math
- Solved
- No attempts yet
Problem
Irma works in a library. Every day she watches visitors take a couple of books from the bookshelf, read them, and put the books back in the same places they took them from. Usually people mess up the order and swap the two books they read. Let's look at one specific bookshelf with books in some order, numbered from to from left to right. The -th visitor takes the books from positions and and puts them back in the same positions, but in the wrong order. After the -th visitor, the book that was at is now at position and vice versa.
In the evening, after the library closes, Irma wants to put all the books back in their places. Each book has a number , the position where that book should end up. To rearrange books, Irma can take any book from the shelf and insert it at the beginning or at the end, so it ends up in the first or the last place on the shelf.
What is the minimum number of moves Irma can make to put all the books in order? Answer this question for the initial placement of books, determined by , and after each visitor that swaps the places of two books.
Input
The first line contains two integers and (; ), the number of books on the shelf and the number of visitors. The next line contains distinct integers (), meaning that the book in the -th position must end up in position .
The next lines describe the library's visitors. Each line contains two integers , (), meaning that the -th visitor swapped the two books at positions and .
Output
Print integers: the minimum number of moves required to sort all books for the initial order, then for the order after the first visitor, ..., after all visitors.
Notes
The initial order of books is . To sort these books, first put the book at the end, then do the same with book . After the first visitor, the bookshelf looks like ; it is enough to move the book to the end. After the second visitor the order of books is . For this order the minimum number of moves is , and there are several ways to reach the final order in moves.