SwapSort
In this problem your goal is to sort an array consisting of n integers in at most nswaps.
For the given array find the sequence of swaps that makes the array sorted in the non-descending order.
Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number of swaps —
your task is to find any sequence that is no longer than n.
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements.
The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109),
where ai is the i-th element of the array. The elements are numerated from 0 to n - 1
from left to right. Some integers may appear in the array more than once.
In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements aiand aj. You can print indices in the pairs in any order.
The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times.
If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.
5 5 2 5 1 4
2 0 3 4 2
6 10 20 20 40 60 60
0
2 101 100
1 0 1
刚被北航网络预赛M题血虐,找到了这一题,以为能给点灵感,结果这题太水了,甚至简单冒泡交换就能过,为了验证我的算法,于是用最小交换次数将数组排序做的,先求出要排序的那个数组从小到大的顺序的目标下标,求出它的环再用数组个数减去环的个数就是最少交换次数。另外用一个结构体数组将其要交换的下标顺序存储起来,最后再输出即可。代码如下:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define siz 100005
using namespace std;
struct node
{
int elem;
int index;
};//结构体数组
int n;
node mp1[siz],mp2[siz];
int cmp(node a,node b)
{
return a.elem<b.elem;
}
int vis[siz];
int jiaohuan(node arr[])//求最小交换次数函数
{
int i;
memset(vis,0,sizeof(vis));
int sum=0;
int j=0;
for(i=0; i<n; i++)
{
if(vis[i]==0)
{
int p=i,l=i;
while(1)
{
vis[p]=1;
p=arr[p].index;
if(p==l) break;
mp2[j].elem=p;
mp2[j].index=arr[p].index;
++j;
}
sum++;
}
}
return n-sum;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=0; i<n; i++)
{
scanf("%d",&mp1[i].elem);
mp1[i].index=i;
}
sort(mp1,mp1+n,cmp);
int ans=jiaohuan(mp1);
cout<<ans<<endl;
for(int i=0; i<ans; i++)
{
cout<<mp2[i].elem<<" "<<mp2[i].index<<endl;
}
}
return 0;
}