加载中...

用 Swap(0, i) 操作进行排序

https://www.acwing.com/problem/content/1555/

#include <iostream>
#include <cstring>

using namespace std;

const int N = 100010;

int n;
int p[N];

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n; i ++ )
    {
        int id;
        scanf("%d", &id);
        p[id] = i;
    }

    int res = 0;
    for (int i = 1; i < n;)
    {
        while (p[0]) swap(p[0], p[p[0]]), res ++ ;
        while (i < n && p[i] == i) i ++ ;
        if (i < n) swap(p[0], p[i]), res ++ ;
    }

    printf("%d\n", res);

    return 0;
}

posted @ 2022-08-23 16:50  英雄不问出处c  阅读(69)  评论(0编辑  收藏  举报