[PAT A1067]Sort with Swap(0, i)
题目描述
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:
Swap(0, 1) => {4, 1, 2, 0, 3}
Swap(0, 3) => {4, 1, 2, 3, 0}
Swap(0, 4) => {0, 1, 2, 3, 4}
Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.
输入格式
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.
输出格式
For each case, simply print in a line the minimum number of swaps need to sort the given permutation.
输入样例
10
3 5 7 2 6 4 9 0 8 1
输出样例
9
解析
- 题目的意思是,首先输入一行数字(0~N-1,不重复,乱序),然后对于每次操作,都只能做0与某个数交换,试问最少需要多少次交换,才能使得原来由乱序变为顺序。
- 这道题目本质是贪心,但是我能力有限,确实没有自己想出来解法,我一开始想到的是每次交换使得0与它所在位置对应的数交换位置,但是发现不对,如果某次交换使得0回到了0位置,这样交换链就断掉了。然后到这里我就想不出来结果了。最后看了人家的代码,思路是跟我一样的,只是遇到0回到0位置的时候,便取后面的一个不在其本位置的数与之交换,最后总能使得所有的数都回到正轨。
- 此外值得学习的是,之前每次都使用常规的方法存放数字比如第一个数是4,那么a[1]=4,第二个数是8,那么a[2]=8这样交换起来十分麻烦,这里涉及到位置的有关信息的时候,我们考虑使用数组存放位置信息,例如第一个数字是8,那么a[8]=1,这样交换就十分的方便,值得我们学习
- 另外在k值(代码中)不能每次都从0开始找,不然会超过时间限制,保证每次k都从上一个位置开始,这样它至多是线性的,不会到n^2级别。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n, cnt = 0, t = 0; //cnt存放交换次数,t存放不在正确位置的数字的个数
int k = 0;
vector<int> nums(100010);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int temp;
scanf("%d", &temp);
nums[temp] = i;
if (temp != i) t++;
}
while (t > 0) {
while(nums[0]) {
swap(nums[0], nums[nums[0]]);
if (nums[0] == 0) { //如果交换之后0回到了原位置,那么t就要减2
cnt++, t -= 2;
}
else {
cnt++, t--;
}
}
if (!nums[0] && !t) break;
else {
while (k < n && (nums[k] == k))k++;
swap(nums[0], nums[k]);
cnt++; t++; //交换之后t需要加1,因为0不在正确位置上了
}
}
printf("%d", cnt);
return 0;
}