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.
Input Specification:
Each input file contains one test case, which gives a positive N (≤10
5
) 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:
10
3 5 7 2 6 4 9 0 8 1
Sample Output:
9
思路:贪心
与其说是贪心更不如说是找规律
- 让元素0和与其下标相等的元素交换。
- 如果0元素下标变成0,从左到右检查第一个错位的元素,并与之交换。
- 继续重复步骤1 2,直到0元素左边无重复元素
一开始思路出现问题。第二步理解成了从左到右检查最大的错位元素,导致测试点1、2运行超时。个人猜测第二步0与任何一个错位元素交换皆可,但是为了不用从左到右检查的for循环(会超时),不妨就从元素1开始,用a保存1。接下来如果到了步骤2,就检查a是否错位即可,不错位就继续a++直到找到错位元素。不错位的元素再怎么交换也不会变成错位,所以不用担心a的左边出现错位元素。
#include <iostream>
using namespace std;
const int N = 100050;
int array[N];
void Swap(int &a, int &b) {
int t = a;
a = b;
b = t;
}
int main() {
int n, res = 0, subZero; cin >> n; //subZero是零的下标
for (int i = 0; i < n; i ++) {
int num;
cin >> num;
array[num] = i;
}
int checkPoint = 1;
while (1) {
if (array[0] != 0) {
Swap(array[0], array[array[0]]);
res ++;
}
else {
while (checkPoint < n && array[checkPoint] == checkPoint) {
checkPoint ++;
}
if (checkPoint == n) break;
Swap(array[0], array[checkPoint]);
res ++;
}
}
cout << res << endl;
return 0;
}