This page is still under construction.

Parts of this page are still being built. What you see may change.

Bookshelf Sorting

Time limit2sMemory limit512 MB

Summary
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 nn books in some order, numbered from 11 to nn from left to right. The ii-th visitor takes the books from positions x_ix\_i and y_iy\_i and puts them back in the same positions, but in the wrong order. After the ii-th visitor, the book that was at x_ix\_i is now at position y_iy\_i 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 p_ip\_i, 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 p_ip\_i, and after each visitor that swaps the places of two books.

Input

The first line contains two integers nn and qq (2≤n≤2⋅1052 \le n \le 2 \cdot 10^5; 0≤q≤2⋅1050 \le q \le 2 \cdot 10^5), the number of books on the shelf and the number of visitors. The next line contains nn distinct integers p_ip\_i (1≤p_i≤n1 \le p\_i \le n), meaning that the book in the ii-th position must end up in position p_ip\_i.

The next qq lines describe the library's visitors. Each line contains two integers x_ix\_i, y_iy\_i (1≤x_i<y_i≤n1 \le x\_i < y\_i \le n), meaning that the ii-th visitor swapped the two books at positions x_ix\_i and y_iy\_i.

Output

Print q+1q + 1 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 qq visitors.

Notes

The initial order of books is (5,1,2,4,3)(5, 1, 2, 4, 3). To sort these books, first put the book 44 at the end, then do the same with book 55. After the first visitor, the bookshelf looks like (5,1,2,3,4)(5, 1, 2, 3, 4); it is enough to move the book 55 to the end. After the second visitor the order of books is (3,1,2,5,4)(3, 1, 2, 5, 4). For this order the minimum number of moves is 33, and there are several ways to reach the final order in 33 moves.

Examples1

  1. Example 1

    Input
    5 2
    5 1 2 4 3
    4 5
    1 4
    
    Expected output
    2
    1
    3