CodeForces 489A SwapSort (选择排序法)
2016-07-22 20:37
393 查看
SwapSort
题目链接:
http://acm.hust.edu.cn/vjudge/contest/121332#problem/ADescription
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
Input5
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; }
相关文章推荐
- Java NIO使用及原理分析 (一)
- android studio recyclerview基础 自定义列表样式
- css属性书写顺序分析
- POJ 2069 Super Star
- hdu5724Chess+SG博弈
- Dialogs(对话框)
- r语言之矩形树状图
- (POJ1325)Machine Schedule(二部图最大匹配)
- Java设计模式-工厂模式
- 8086汇编语言自学经验分享 新手汇编源代码---多段实例
- scanf()函数
- 基础知识
- CSVs in Python
- 【杭电2124】Repair the Wall
- Java调用C++ API完整示例(dll)
- NYOJ263精挑细选
- Java wait(long arg)方法的使用
- Ubuntu 设定壁纸自动切换的shell脚本
- golang substring方法的几种实现
- 用递归函数和栈操作逆序一个栈