题目链接:http://codeforces.com/contest/489

A:SwapSort

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.

题意:给出包含n个数的数组(一个数可以出现多次),每次可以交换任意两个数,最多交换n次后,要求数组变成非降序数列。求出这样的一个交换操作(不要求求出最少交换次数)

解法:首先我们需要知道,一个数列最终要变为非降序,要么原数列中最小的数一定要在排完序的数列中的首位置。剩下的就迎刃而解了。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<cmath>
 6 #include<algorithm>
 7 #define inf 0x7fffffff
 8 using namespace std;
 9 const int maxn=3000+10;
10 int an[maxn];
11 int cn[maxn][2];
12 int cnt;
13 int main()
14 {
15     int n;
16     while (scanf("%d",&n)!=EOF)
17     {
18         cnt=0;
19         for (int i=0 ;i<n ;i++) scanf("%d",&an[i]);
20         for (int i=0 ;i<n ;i++)
21         {
22             int minnum=an[i],k=i;
23             for (int j=i+1 ;j<n ;j++)
24             {
25                 if (an[j]<minnum)
26                 {
27                     minnum=an[j] ;k=j ;
28                 }
29             }
30             if (k==i) continue;
31             cn[cnt][0]=i;
32             cn[cnt][1]=k;
33             swap(an[i],an[k]);
34             cnt++;
35         }
36         printf("%d\n",cnt);
37         for (int i=0 ;i<cnt ;i++) printf("%d %d\n",cn[i][0],cn[i][1]);
38     }
39     return 0;
40 }
View Code

相关文章:

  • 2021-08-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-05
  • 2021-08-12
  • 2021-04-24
  • 2021-12-04
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-17
  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案