PAT甲1067 Sort with Swap(0, i)(25 分)

#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;

int pos[100010];
int A[100010];
int N;

int main()
{
    scanf("%d",&N);
    int num=0;
    for(int i=0;i<N;i++)
    {
        scanf("%d",&A[i]);
        pos[A[i]]=i;
        if(pos[A[i]]==A[i]&&A[i]!=0)
        {
            num++;
        }
    }
    int step=0;
    int k=1;
    while(num<N-1)
    {
        if(pos[0]!=0)
        {
            swap(pos[0],pos[pos[0]]);
            num++;
            step++;
        }
        else
        {
            while(k<N)
            {
                if(pos[k]!=k)
                {
                    swap(pos[0],pos[k]);
                    step++;
                    break;
                }
                k++;
            }
        }
    }
    printf("%d",step);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/82193465