[POJ 1674] Sorting by swapping

Source: Internet
Author: User

sorting by swapping
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 9514 Accepted: 5094

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 are 2, 3, 5, 4, 1, we can sort them in the following-in-the-loop:
2 3 5 4 1 1 3 5 4 2 1 3 2 4 5 1 2 3 4 5
Here three swaps has 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 <=) that indicates the number of test cases. Then follow the T cases. Each case contains the 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 would be being only one integer, which are the least number of swaps needed to get the sequence 1, 2, 3, ..., n from the initial permutation.

Sample Input

231 2 352 3 5 4 1

Sample Output

03

Source

Introduction to the definition of POJ monthly--2004.06.27 weak person permutation group
#include <iostream>#include<algorithm>#include<cstdio>using namespacestd;#defineN 10010intN;intA[n];intMain () {intT; scanf ("%d",&T);  while(t--) {scanf ("%d",&N);  for(intI=1; i<=n;i++) scanf ("%d",&A[i]); intCnt=0;  for(intI=1; i<=n;i++)        {             while(a[i]!=i) {swap (a[i],a[a[i]); CNT++; }} printf ("%d\n", CNT); }    return 0;}

[POJ 1674] sorting by swapping

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.