[POJ 1674] Sorting by Swapping

來源:互聯網
上載者: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 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

231 2 352 3 5 4 1

Sample Output

03

Source

POJ Monthly--2004.06.27 弱人 置換群定義入門題目
#include <iostream>#include <algorithm>#include <cstdio>using namespace std;#define N 10010int n;int a[N];int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        for(int i=1;i<=n;i++) scanf("%d",&a[i]);        int cnt=0;        for(int i=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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.