题意
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.
输出格式
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
思路
hashTable数组,记录数字index的实际位置hashTable[index]
fault记录除0之外位置不对的数量
k记录位置不对的最小的下标
只要hashTable[0]不为0,将hashTable[0]与hashTable[hashTable[0]]交换,ans++
当hashTable[0]为0,检查fault是否为0,为0就结束,否则交换后继续
代码
/**
* @tag PAT_A_1067
* @authors R11happy (xushuai100@126.com)
* @date 2017-2-13 19:42-20:31
* @version 1.0
* @Language C++
* @Ranking 1110/1225
* @function null
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100010;
int hashTable[maxn];
int num[maxn];
int main(int argc, char const *argv[])
{
int N;
int ans = 0;
int fault = 0; //记录除0以外不在本位的数量
int k = 1; //存放除0以外,不在本位上最小的数
scanf("%d", &N);
memset(hashTable, -1, sizeof(hashTable));
for (int i = 0; i<N; i++)
{
scanf("%d", &num[i]);
hashTable[num[i]] = i;
if( i != 0 && hashTable[i] != i) fault++; //记录不在本位的数量
}
while (fault > 0)
{
if (hashTable[0] != 0)
{
// swap(num[hashTable[0]], num[hashTable[hashTable[0]]]);
swap(hashTable[0], hashTable[hashTable[0]]);
ans++;
fault--;
}
else
{
while(k < N) //要单独记录最小的位置错误的下标,不要每次遍历寻找,不然会超时
{
if (hashTable[k] != k)
{
// swap(num[hashTable[0]], num[hashTable[ii]]);
swap(hashTable[0], hashTable[k]);
ans++;
break;
}
k++;
}
}
}
printf("%d\n", ans);
// for (int i = 0; i <N; i++)
// {
// printf("%d ", num[i]);
// }
// printf("\n");
// for (int i = 0; i <N; i++)
// {
// printf("%d ", hashTable[i]);
// }
return 0;
}
收获
当发现从头遍历运行超时
,考虑单独一个k,记录最小fault的下标