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 (≤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和该数字进行更换。

但是只用上述的方法会出现测试点1、2超时的情况,因此,需要用到一个减少遍历寻找次数的小技巧:使用一个变量min_sub记录当前未归位的最小数字。这样,当上述的0在本位(作为第一个数)的时候,以for顺序查找第一个不在本位的数字时,不需要从0开始,只需要从min_sub开始。

在数据结构方面,本题以两个哈希散列存储每一个数字是否存入本位(以0代表未存入本位,以1代表已经归位)以及每一个数字的下标。

易错点

测试点2-极端情况,输入数据降序排列,我的自测用例如下:

5
4 3 2 1 0

交换的过程是:

5
4 3 2 1 0
0 3 2 1 4
1 3 2 0 4
1 0 2 3 4
0 1 2 3 4

该测试点既检测了0在与不在第一个数字如何调换的部分,还检测了能否在规定的时间内完成运行。

代码

#include<bits/stdc++.h>
using namespace std;
int N,Hash[100001],A[100001];
int min_sub;

int Swap(int b){
    int temp = A[0];
    A[0] = A[b];
    A[b] = temp;
    Hash[0] = (A[0]==0)?1:0;
    Hash[b] = (A[b]==b)?1:0;
    return 1;
}

int main(){
    int i,temp;//N≤10^5
    scanf("%d",&N);
    long int num = 0;//最少交换次数
    int k=0;//k是下标
    for (i=0;i<N;i++)
    {
        scanf("%d",&temp);//记录每一个数据的下标
        A[temp] = i;//记录每一个数字的下标
        if (temp==i)//已经在位置上
            Hash[i] = 1;
    }
    while (k<N){
        if (A[0]!=0)
            num+=Swap(A[0]);
        else
        {
            for (i=min_sub;i<N;i++)
            {
                if (Hash[i]==0)
                {
                    min_sub = i;//不在本位上的数字的最小数
                    break;
                }
            }
            for (k=min_sub;k<N;k++)
            {
                if (Hash[k]==0)
                {
                    num+=Swap(k);
                    break;//未排列好,进行下一次查找最小的未在位置上的数字
                }
            }
        }
    }
    printf("%ld",num);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值