PAT A1067 Sort with Swap(0,*) (25)(25 分)-----贪心法1---典型

总结:

1.算法还是很好想,如果0不在0位,就将0与该在这个位置上的数交换,如果0在0位,就把它与任意一个不在正确位置上的数交换。写的时候要注意细节,我用了一个pos[i]来表示i在start数组的位置,交换过后不仅要交换数字,还要交换位置。用了一个cnt来确定什么时候停止循环,cnt--不再正确位置上的数的个数,当其等于0的时候停止循环

2.要注意如果一个数(下标为index)和0交换过了后再下一次0出现再0位置上时,这个Index就肯定处在正确位置上了,下一次找直接从index开始找

代码:

#include<iostream>
using namespace std;
int start[110000];
int pos[110000];
void swap1(int&a,int&b)
{
    int temp = a;
    a = b;
    b = temp;
}
int main()
{
    int m;
    int cnt = 0;
    int total = 0; int index = 1;
    scanf("%d",&m);
    for (int i = 0; i < m; i++)
    {
        scanf("%d",&start[i]);
        if (start[i] != 0 && start[i] != i)cnt++;
        pos[start[i]] = i;
    }
    int sum = 0;
    while (cnt>0)
    {
        if (pos[0] != 0)
        {
            total = pos[0];                  //0的位置
            swap1(start[total], start[pos[total]]); //pos[total]--total的位置
            cnt--;swap1(pos[0],pos[total]); sum++;
        }
        else                //0在0位
        {
            //交换start[0]和任意一个不在位置上的数
                                     //从第一个元素开始看,如果不是正确位置,交换
            while (start[index] == index)
            {
                index++;
            }
            swap1(start[0],start[index]);
            pos[0] = index; pos[start[0]] = 0;
            sum++;
        }

    }
    printf("%d",sum);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值