PTA-mooc完整题目解析及AC代码库:PTA(拼题A)-浙江大学中国大学mooc数据结构全AC代码与题目解析(C语言)
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 (≤ 1 0 5 10^5 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
题目分析
给定一个长度为N的乱序数值序列,里面的数字取值为0~N-1。假定排序过程中只能使用一个swap(0, i)函数,该函数可以交换0和任意数字位置,即排序只能通过不断和0进行交换来达到有序状态。
题目要求输出这种交换方式下最小交换次数。
解法分析
这道题一开始我是没有什么思路的,去网上查找了相关资料后,大概发现了有两类解法:数环法和贪心法。这里的数环法是课程给出的参考解法。
数环法
遍历整个序列,按照环的方式计算交换次数。
这里存储的数据是按照输入数据顺序存储的,因此这种情况下,数组索引i
表示第i
个位置,元素arr[i]
表示i
位置上存储的实际元素值。
如果遍历过程中,遍历到包含0的环,则该环的交换次数为环的长度减1;而如果遍历到不包含0的环,则首先需要将0换入该环,即交换次数计数加1,然后换入后的交换次数等于新环的长度减1,也就等于原环的长度。
贪心法
以零元素所占位置作不停交换来计数。
这里存储的数据与上一种方法不同,该方法中数组索引i
表示元素值,而arr[i]
表示该元素当前所在位置。
在遍历所有元素的计算过程中,将0元素所在位置置为哨兵,当0不在0位置上时,将0与当前其所占位置应该存放的元素进行交换直到0元素归位,这时若仍有元素还未归位,则将0与其交换,这时0又不在其位置上了,那么继续执行上述步骤直到所有元素归位。
解法比较
相比而言,两种方法基本上都需要遍历一遍整个数组,时间复杂度都为O(N),但贪心法需要不断的进行元素交换步骤,较为耗时,所以相较而言数环的方法更好。
数环法代码:
#include <stdio.h>
#include <stdlib.h>
void solve();
int main()
{
solve();
return 0;
}
void solve()
{
int i, n, tmp, num, *arr;
scanf("%d", &n);
arr = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}
num = 0; i = 0;
if (arr[0] == 0) i = 1;
for (; i < n; ++i) {
if (arr[i] != i) {
++num; // 假设0不在环里,则此处需要将0额外换入该环中,因此多执行一次swap
while (arr[i] != i) {
if (arr[i] == 0) // 说明0在这个环里,无需额外换入环中,抵消外层的+1计数,并且本身无需再加1,因为包含0的环交换次数等于环长度减1
--num;
else
++num;
tmp = arr[i];
arr[i] = i;
i = tmp;
}
}
}
printf("%d", num);
free(arr);
}