Minimum Number of swap for a permutation
Description
Given an array of permutation with size of , find the number of operations that one should execute so that the array is in sorted. In an operation, one could choose two indices and such that and swap the value of and .
For example, for and , the number of operations that should be done is . We could do the operation on pair of indices and .
Solving the Problem
Intuition
One can observe that there may exists some kind of circuit like pattern in . I use the term circuit loosely here. A circuit is defined as a set of number (that represents indices in the ) such that the graph that it could create—which will be later explained—resembles a cycle loop. It’s obvious that a graph would be defined by its . It’s obvious that the is defined by set of indices in the circuit itself. The set could be created by iteratively augmenting edge of for .
The graph is a directed cyclic type because for each node , where , we know that there is only other node pointing towards node —due to there exists only 1 other node that should replace such that the node would be in its correct position—and only 1 other node such that the correct position of node is occupied by node .
Solution
We could solve each circuit independently—because each node in circuit does not need to “interfere”/swap with the other circuit.
For each circuit , the number of swap needed is . For each , we can arbitarily choose a node and do swap it to its correct position. The iteration continues until there only exists 2 nodes in that is still not in the right place. Because there exists only 2 remaining node, it’s obvious that we could just swap—just do operation—and both node are swapped in a right place.
Therefore, the number of minimum swap is where is the set of circuit that exists in . However, this equation could be further simplified. We could do the distribution rules and change the answer into . The first part of the summation is equals to as the sum of size of all circuits are equal to the number of element in the and the secnd part is equal to the number of circuit, i.e. .
Because of that, the simplified solution are - .