1067 Sort with Swap(0, i) (25 分)
Given any permutation of the numbers {0, 1, 2,…, N−1}, it is easy to sort them in increasing order. But what if Swap(0, *)
is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:
1 | Swap(0, 1) => {4, 1, 2, 0, 3} |
Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.
Input Specification:
Each input file contains one test case, which gives a positive N (≤105) followed by a permutation sequence of {0, 1, …, N−1}. All the numbers in a line are separated by a space.
Output Specification:
For each case, simply print in a line the minimum number of swaps need to sort the given permutation.
Sample Input:
1 | 10 |
Sample Output:
1 | 9 |
作者: CHEN, Yue
单位: 浙江大学
时间限制: 200 ms
内存限制: 64 MB
代码长度限制: 16 KB
题目大意
给出一组数据,每次只能和0号元素交换,问最少几次交换可以把数组变为有序
分析
一开始没有什么思路,在网上找了一些解法也比较晦涩,例如柳婼のblog。可能是我太菜:(。后来找到一个思路比较直观1067. Sort with Swap(0,*) (25)。不同与第一种解法,这里的a[i]就是i位置上的元素,而不是元素i的位置,符合日常使用习惯,比较直观。当a[0]!=0
时,把a[0]上的元素交换到相应位置。当a[0]==0
时,找到第一个不在正确位置上的元素,交换到0位置,下一次交换即可换到正确位置上。
代码
1 |
|
其他
这题可以扩展一下,如果说可以交换任意两个元素而不是只能同0位置交换,那么最小交换次数是多少。可以参考使序列有序的最少交换次数