码迷,mamicode.com
首页 > 移动开发 > 详细

[POJ 1674] Sorting by Swapping

时间:2015-04-15 23:21:09      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:

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

2
3
1 2 3
5
2 3 5 4 1

Sample Output

0
3

Source

 
置换群定义入门题目
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
#define N 10010

int 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

标签:

原文地址:http://www.cnblogs.com/hate13/p/4430380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!