PAT甲级刷题记录——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

思路

这题我只想说……选择的方向正确能让你轻松一大半……

我一开始用data[i] = num来记录(下标i是位置,num是数),虽然一下子就能AC除了两个超时以外的所有测试点,但是超时那两个一直改不好:因为这么写的话,0和某个数交换之后,虽然知道交换之后0的位置在哪,但是并不知道哪个数的值正好等于0的位置,所以还是得从头遍历来找那个数(超时就超在这个地方)……差不多卡了一个多小时,无奈,只好看晴神的思路,改成了用pos[num] = i来记录(下标num是数,i是位置),这样就能通过两次pos来找到所要交换的那个数所在的位置了(因为值存的就是位置,所以swap(pos[x], pos[y])就是交换x、y两个数的位置)。

题目意思还是很简单的,就是通过0和它本身所在位置的数一直交换(比如4 0 2 1 3,0所在的位置是1,因此,0和1交换),直到整个序列有序。

这里还要分两种情况讨论:

  • 0不在位置0,那么就一直交换,交换次数cnt++,剩余需要处理的数left–(left记录的是除0以外不在本位上数的个数);
  • 0在位置0,那么就找到后面第一个不满足有序的数,进行交换(最终要求是要让所有数的pos[num] = num,这样就是一个递增序列了),并且交换次数cnt++(这里不需要处理left的值)。

最后提醒一下自己:以后要是遇到位置和数有关的题目,尽量把数作为下标位置作为值(原先的做法想得头疼)……

代码

#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<iostream>
using namespace std;
const int maxn = 100010;
int pos[maxn] = {0};
int checkPos(int a[], int len){
    for(int i=0;i<len;i++){
        if(a[i]!=i){
            return i;
        }
    }
}
bool judge(int a[], int len){
    for(int i=0;i<len;i++){
        if(a[i]!=i) return false;
    }
    return true;
}
int main()
{
    int N;
    scanf("%d", &N);
    int left = N-1;
    for(int i=0;i<N;i++){
        int num;
        scanf("%d", &num);
        pos[num] = i;//num的位置是i
        if(num==i&&num!=0) left--;
    }
    int cnt = 0;
    int firstNum = 1;
    while(left>0){
        if(pos[0]==0){
            while(firstNum<N){
                if(pos[firstNum]!=firstNum){
                    swap(pos[0], pos[firstNum]);
                    cnt++;
                    break;
                }
                firstNum++;
            }
        }
        while(pos[0]!=0){
            swap(pos[0], pos[pos[0]]);
            cnt++;
            left--;
        }
    }
    printf("%d", cnt);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值