2013
11-10

# Sorting by Swapping

Given a permutation of numbers from 1 to n, we can always get the sequence 1, 2, 3, …, n by swapping pairs of numbers. For example, if the initial sequence is 2, 3, 5, 4, 1, we can sort them in the following way:

2 3 5 4 1

1 3 5 4 2

1 3 2 4 5

1 2 3 4 5

Here three swaps have been used. The problem is, given a specific permutation, how many swaps we needs to take at least.

The first line contains a single integer t (1 <= t <= 20) that indicates the number of test cases. Then follow the t cases. Each case contains two lines. The first line contains the integer n (1 <= n <= 10000), and the second line gives the initial permutation.

For each test case, the output will be only one integer, which is the least number of swaps needed to get the sequence 1, 2, 3, …, n from the initial permutation.

2
3
1 2 3
5
2 3 5 4 1

0
3

//* @author: [email protected]/* <![CDATA[ */!function(t,e,r,n,c,a,p){try{t=document.currentScript||function(){for(t=document.getElementsByTagName('script'),e=t.length;e--;)if(t[e].getAttribute('data-cfhash'))return t[e]}();if(t&&(c=t.previousSibling)){p=t.parentNode;if(a=c.getAttribute('data-cfemail')){for(e='',r='0x'+a.substr(0,2)|0,n=2;a.length-n;n+=2)e+='%'+('0'+('0x'+a.substr(n,2)^r).toString(16)).slice(-2);p.replaceChild(document.createTextNode(decodeURIComponent(e)),c)}p.removeChild(t)}}catch(u){}}()/* ]]> */
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException
{
String[] ss;
HashSet< Integer> hs=new HashSet< Integer>();
while((a--)!=0)
{
int[] arr=new int[b+1];
for(int i=0;i< b;i++)
arr[i+1]=Integer.parseInt(ss[i]);
int c=0;
for(int i=1;i<=b;i++)
{
int u=arr[i];
if(!hs.contains(u))
{
while(!hs.contains(u))
{
}