PAT_A 1067 Sort with Swap(0, i)

PAT_A 1067 Sort with Swap(0, i)

分析

题意为输入(0,...,i, ..., N-1)这N个数任意顺序组成的序列,需要通过与 数字0 交换多次直至递增有序,需要计算最少的交换次数。

求解过程中需要充分利用输入的数字的性质,即从0至N-1这N个不重复的正整数。

使用数组 nums[N] 存储数字,且 nums[i]=t 表示 数字i 在位置t上,显然最终应该 nums[i]=i, 例如数字0最终应该存储在位置0上,即 nums[0]=0。鉴于只能与数字0做交换,因此设置位置0为哨兵位,并通过循环检验每个位置1后的位置上的数字是否与最终结果相符,若不符则与0交换;且若nums[0]=0出现在排序完成前,需要与任意不在位的数字替换,并继续循环的过程。

所以在读入数据后,应该进行如下操作:

  • 当 nums[0] != 0 时, 将位置0此时数字,与其最终应在的位置的 此时的数字做交换,即 swap(nums[0], nums[nums[0]])
  • 若nums[0]==0 且序列仍未有序, 将位置0上的数字,也就是0,与第一个不在最终位置的数字做交换

PAT_A 1067 Sort with Swap(0, i)

题目的描述

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

AC的代码

#include<bits/stdc++.h>

using namespace std;

int main(){
    int N, ans = 0;
    scanf("%d",&N);
    int nums[N];
    for(int i=0;i<N;i++){
        int t;
        scanf("%d",&t);
        nums[t]=i;
    }
    for(int i=1;i<N;i++){
        while(nums[0]!=0){
            swap(nums[0],nums[nums[0]]);
            ans++;
        }
        if(nums[i]!=i){
            swap(nums[i],nums[0]);
            ans++;
        }
    }
    printf("%d\n",ans);
    return 0;
}
posted @ 2022-09-12 16:30  ghosteq  阅读(9)  评论(0编辑  收藏  举报