您的位置:首页 > 移动开发

poj 1674 Sorting by Swapping

2016-08-20 09:46 656 查看
Sorting by Swapping

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 9698 Accepted: 5191
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

POJ Monthly--2004.06.27 弱人

一道选择排序题目,但是用传统的选择排序写会超时,就像我第一次交这道题目一样,但是思维不应受限于选择排序,我们可以创建两个数组,一个存下要处理的序列(a数组),一个存下目标序列(b数组),a数组与b数组一一对比,在对比过程中如果不同则在a中找着应该放在这个位置的元素,进行交换,这样,从a的首元素一直到尾元素遍历一遍也就把a数组排成了b数组的模样。

PS:在这道题目中b数组所存序列是一个传统的升序,但是即使题目要求的是自定义的目标序列也是一样处理,升序只是一般情况中的一个特殊情况。

//Code:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int maxn=10005;
int a[maxn];
int b[maxn];

int main()
{
//freopen("in.txt","r",stdin);
int t;
scanf("%d",&t);
while(t--)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
b[i]=i;
}
int ans=0;
for(int i=1;i<=n;i++)
{
if(a[i]!=b[i])
{
for(int j=i+1;j<=n;j++)
{
if(a[j]==b[i])
{
swap(a[i],a[j]);
ans++;
break;
}
}
}
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: