PAT A1067 Sort with Swap(0,*) (25)

解题思路

  1. 按照题中描述模拟一遍,可以发现,每次“0”都与一个没有归位的数字交换,而且这个数字的最终位置就是“0”所在的位置。
  2. 中间会出现“0”回到原位的情况,这是只要和一个未归位的数字再交换一下,继续即可。 所以,思路大体上就是交换并记录次数。
  3. 数据的存储有一点技巧,由于题设给定,数字是连续的,所以存储时存的是当前数字所在的位置。这样在后面查找以及交换时非常方便。
  4. Swap可以使用Algorithm中的,也可以自己写。

AC代码

#include <cstdio>
#include <algorithm>
using namespace std;
// 排序 只能通过和 0 交换位置
const int maxn = 100010;
int pos[maxn];  // 存放当前数字所在的位置

int main() {
    int a, num;
    scanf("%d", &num);

    int left = num - 1; //还剩余多少数字未归位
    for (int i = 0; i < num; i++)
    {
        scanf("%d", &a);
        pos[a] = i;
        if (a == i && a != 0)
            left--;
    }
    int count = 0,  x = 1;
    while (left > 0)
    {
        if (pos[0] == 0)        // 若 0 回到了第一位,但还没有排好序,和第一个没归位的数字换一下
        {
            while (x < num) {   // 找到第一个未归位的数字
                if (pos[x] != x)
                {
                    swap(pos[0], pos[x]);
                    count++;
                    break;
                }
                x++;
            }
        }
        //Swap
        while (pos[0] != 0)
        {
            swap(pos[0], pos[pos[0]]);
            count++;
            left--;
        }
    }
    printf("%d\n", count);

    return 0;
}

下面再贴一个一开始采取的常规存储方式超时的算法。

#include <cstdio>
#include <algorithm>
using namespace std;
// 排序 只能通过和 0 交换位置
const int maxn = 100010;
int num, n[maxn], m[maxn];
bool flag[maxn];    // 数字为0~n-1

bool cmp(int a[], int b[]) {
    for (int i = 0; i < num; i++)
        if (a[i] != b[i]) return false;
    return true;
}

int main() {
    scanf("%d", &num);
    for (int i = 0; i < num; i++)
    {
        scanf("%d", &n[i]);
        m[i] = n[i];
    }
    sort(m, m + num);   // 辅助数组排序

    int count = 0, pointer0 = 0, pointerN = 0, x = 1;   // pointer0为0的位置
    while (n[pointer0++] != 0); // 找到0的位置
    pointer0--;
    while (!cmp(n, m))
    {
        if (pointer0 == 0)      // 若 0 回到了第一位,但还没有排好序,和第一个没归位的数字换一下
        {
            while (flag[n[x++]]);   // 找到第一个未归位的数字
            int t = n[pointer0];
            n[pointer0] = n[x - 1];
            n[x - 1] = t;
            count++;
        }
        while (n[pointerN++] != pointer0);      // 找到 0 所在位置的数字
        pointerN--;
        flag[n[pointerN]] = true;               // 标记此数以归位
        //Swap
        int temp = n[pointer0];
        n[pointer0] = n[pointerN];
        n[pointerN] = temp;
        pointer0 = pointerN;
        pointerN = 0;
        count++;
    }
    printf("%d\n", count);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值