CodeForces 489A SwapSort (选择排序法)

时间:2024-08-01 23:06:56

SwapSort

题目链接:

http://acm.hust.edu.cn/vjudge/contest/121332#problem/A

Description

In this problem your goal is to sort an array consisting of n integers in at most n swaps. 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.

Input

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.

Output

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 ai and 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.

Sample Input

Input

5

5 2 5 1 4

Output

2

0 3

4 2

Input

6

10 20 20 40 60 60

Output

0

Input

2

101 100

Output

1

0 1

题意:

给出一个数组,进行不超过n次交换操作后保持升序;

题解:

由于没有要求输出最少的次数;

直接跑一遍选择排序法就可以了,复杂度有点高,不过可以接受.

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#define LL long long
#define eps 1e-8
#define maxn 3300
#define inf 0x3f3f3f3f
#define IN freopen("in.txt","r",stdin);
using namespace std; int n;
int a[maxn];
int ans[maxn+100][2]; int main(int argc, char const *argv[])
{
//IN; int ca = 1;
while(scanf("%d", &n) != EOF)
{
int cnt = 0;
for(int i=1; i<=n; i++) scanf("%d", &a[i]);
//sort(a+1, a+1+n);
for(int i=1; i<=n; i++) {
int p=i, mimi = a[i];
for(int j=i+1; j<=n; j++) {
if(a[j] < mimi) mimi = a[p=j];
}
if(p==i) continue;
swap(a[i], a[p]);
//printf("%d %d\n", i-1,p-1);
ans[cnt][0]=i-1;
ans[cnt][1]=p-1;
cnt++;
} printf("%d\n", cnt);
for(int i=0; i<cnt; i++)
printf("%d %d\n", ans[i][0], ans[i][1]);
} return 0;
}