Given a permutation of misplaced monsters, find the minimum number of swaps needed to sort all monsters into their correct chambers.
Medium4ArrayGraphImplementationMathNo attempts yetTime limit5sMemory limit512 MBIn the Dark Ride attraction a narrow gauge train carries the visitors through a sequence of chambers. Each chamber holds one IT monster, programmed to scare the visitors in various wicked ways. For strange and obscure reasons, some of the monsters were installed in the wrong chambers. Freddie and Morcia, who are employees and not monsters, have to reinstall the monsters in the correct chambers.
To avoid extra confusion and danger, Freddie and Morcia work in episodes. In one episode they choose two distinct chambers. Freddie picks the monster in one of the chambers and carries it to the other chamber, while Morcia picks the monster in that other chamber and carries it to the chamber Freddie has just emptied. One episode therefore swaps the monsters of two chambers. After some number of episodes every monster has to sit in its correct chamber. Moving monsters is tedious work, so Freddie and Morcia want to minimize the number of episodes.
The input holds several test cases and ends at the end of the file. Each test case consists of two lines.
The first line contains one integer N (1≤N≤2×105), the number of chambers. The chambers are labeled 1,2,…,N and the monsters are labeled 1,2,…,N as well. The label of each chamber equals the label of the monster that belongs in it.
The second line contains the N labels of the monsters currently installed in the chambers. The monster given by the first label is installed in chamber 1, the monster given by the second label is installed in chamber 2, and so on.
For each test case, print one line with the minimum number of episodes needed to install every monster in its correct chamber.