Codeforces Round #277.5 (Div. 2)-A. SwapSort
http://codeforces.com/problemset/problem/489/A
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.
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 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 = jand 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
解题思路:n个数字,通过k次交换使得他们升序。贪心,每次找到没有找到的最小的数字的下标与当前下标的数字交换即可
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <time.h>
6 #include <math.h>
7
8 using namespace std;
9
10 const int MAXN = 3010;
11 int n, num[MAXN], from[MAXN], to[MAXN];
12
13 void solve(){
14 memset(from, 0, sizeof(from));
15 memset(to, 0, sizeof(to));
16 int i, j, k = 0, minnum, t;
17 for(i = 0; i < n - 1; i++){
18 minnum = i;
19 for(j = i + 1; j < n; j++){
20 if(num[j] < num[minnum]){
21 minnum = j;
22 }
23 }
24 if(i == minnum){
25 continue;
26 }
27 from[k] = i;
28 to[k] = minnum;
29 t = num[i], num[i] = num[minnum], num[minnum] = t;
30 k++;
31 }
32 printf("%d\n", k);
33 for(i = 0; i < k; i++){
34 printf("%d %d\n", from[i], to[i]);
35 }
36 }
37
38 int main(){
39 int i;
40 while(scanf("%d", &n) != EOF){
41 for(i = 0; i < n; i++){
42 scanf("%d", &num[i]);
43 }
44 solve();
45 }
46 return 0;
47 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步