PAT 1067 Sort with Swap(0, i) (貪心法)
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 (≤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:
10
3 5 7 2 6 4 9 0 8 1
Sample Output:
9
解題思路
基本思路是,我們依次拿0與0所在位置代表的那個數(比如測試用例中0的位置為7)進行交換,最後得到有序序列
不過這樣計算會出現一種特殊情況:就是0和0位置那個數發生了交換,那麼演算法到這裡就終止了
遇到這種特殊情況,只需將0與最小的那個不在本位上的數交換就可以了。
也就是說
i != m[i]時,將0與數交換, i = m[i],繼續遍歷,程式碼如下:
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
using namespace std;
const int MAXN = 100010;
int Numbers[MAXN];
int HashTable[MAXN]; //用來儲存一個數所在的位置數
int main() {
int N;
scanf("%d", &N);
for (int i = 0; i < N; ++i) {
scanf("%d", &Numbers[i]); //依次讀入
HashTable[Numbers[i]] = i;
}
int pos = HashTable[0]; //給出0的位置
int counter = 0;
//中斷迴圈條件:當每個i == m[i]時
while (true) {
int tempPos = pos;
int i;
if (tempPos == 0) {
//遍歷尋找一個 i != m[i]的數字
for (i = 1; i < N; ++i) {
if (i != Numbers[i]) {
swap(Numbers[tempPos], Numbers[i]);
swap(HashTable[Numbers[tempPos]], HashTable[Numbers[i]]);
counter++;
pos = i;
break;
}
}
if (i == N) {
break; //陣列已有序 退出迴圈即可
}
}
else {
pos = HashTable[pos];
swap(Numbers[pos], Numbers[tempPos]);
swap(HashTable[Numbers[pos]], HashTable[Numbers[tempPos]]);
counter++;
}
}
printf("%d", counter);
system("PAUSE");
return 0;
}