[PAT A1067]Sort with Swap(0, i)

博客围绕PAT A1067题目展开,该题要求用Swap(0, *)操作将乱序数字序列排序,求最少交换次数。解析指出题目本质是贪心算法,给出解题思路,还提到用数组存位置信息方便交换,以及k值不从0开始避免超时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[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 (≤10​5​​) 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

解析

  1. 题目的意思是,首先输入一行数字(0~N-1,不重复,乱序),然后对于每次操作,都只能做0与某个数交换,试问最少需要多少次交换,才能使得原来由乱序变为顺序。
  2. 这道题目本质是贪心,但是我能力有限,确实没有自己想出来解法,我一开始想到的是每次交换使得0与它所在位置对应的数交换位置,但是发现不对,如果某次交换使得0回到了0位置,这样交换链就断掉了。然后到这里我就想不出来结果了。最后看了人家的代码,思路是跟我一样的,只是遇到0回到0位置的时候,便取后面的一个不在其本位置的数与之交换,最后总能使得所有的数都回到正轨。
  3. 此外值得学习的是,之前每次都使用常规的方法存放数字比如第一个数是4,那么a[1]=4,第二个数是8,那么a[2]=8这样交换起来十分麻烦,这里涉及到位置的有关信息的时候,我们考虑使用数组存放位置信息,例如第一个数字是8,那么a[8]=1,这样交换就十分的方便,值得我们学习
  4. 另外在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;
}
水平有限,如果代码有任何问题或者有不明白的地方,欢迎在留言区评论;也欢迎各位提出宝贵的意见!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值