poj 1674 Sorting by Swapping

it2024-04-16  110

Sorting by Swapping

Time Limit: 1000MSMemory Limit:10000K

Total Submissions: 8109Accepted:4300

Description

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.

Input

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.

Output

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.

Sample Input

2 3 1 2 3 5 2 3 5 4 1

Sample Output

0 3   #include<iostream> using namespace std; void swap(int &a,int &b) { int temp=b; b=a; a=temp; } int main() { int n; int t; int i,j; int pos; int change; int nums[10001]; cin>>t; while(t--) { cin>>n; for(i=1;i<=n;i++) cin>>nums[i]; change=0; for(i=1;i<=n;i++) { for(j=i;j<=n;j++) { if(nums[j]==i) { pos=j; break; } } if(pos!=i) { swap(nums[pos],nums[i]); change++; } } cout<<change<<endl; } return 0; }

转载于:https://www.cnblogs.com/w0w0/archive/2011/11/21/2257746.html

最新回复(0)