PAT甲级1067 Sort with Swap(0, i) (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​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 , 1 , . . . , N − 1 } \{0,1,... , N-1\} { 0,1,...,N1}这个序列的变式,不难看出,这里说的排序其实就是把每个数存放到数组对应的下标那里。我们可以用一个数组pos表示每个数对应的位置,在0的位置不为0的情况下,我们一直进行第一个数与0的交换,同时count++,如果0已经被调到第一个位置,我们就看还有没有数字是没有“站”对地方的,如果有,则做一次交换,重新进入循环;如果都在自己该在的位置,则输出count即可。

三、AC代码

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    
    
    int n;
    scanf("%d", &n);
    vector<int> pos(n);
    for (int i=0; i<n; i++) //初始化pos数组,表示每个数字对应的位置
    {
    
    
        int temp;
        scanf("%d", &temp);
        pos[temp] = i;
    }
    int count = 0;  //进行了几次交换
    int checkPos = 1;   //已经就位的数字个数
    bool sorted = false;    //标记是否已经排序完成
    while (!sorted) //swap(0, i)
    {
    
    
        if (pos[0] != 0)
        {
    
    
            int i = pos[0]; //暂存0的位置
            pos[0] = pos[i];    //将0交换过去
            pos[i] = i; //将i移到一开始0的位置
            count++;
            continue;
        }
        //检查是否仍存在错位
        while (checkPos<n && pos[checkPos]==checkPos)   checkPos++;
        if (checkPos==n)    sorted = true;  //n个元素全都在正确的位置
        else    //否则要用0再去和不在正确位置的数字交换
        {
    
      
            //swap(0, i)
            pos[0] = pos[checkPos];
            pos[checkPos] = 0;
            count++;
        }
    }
    printf("%d\n", count);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108705021