个人练习-PAT甲级-1067 Sort with Swap(0, i)

题目链接https://pintia.cn/problem-sets/994805342720868352/problems/994805403651522560

思路就是贪心法。但贪心法为什么正确没搞明白。。按照思路写了一遍结果测试点1、2超时了。于是看了柳神的解答抄了一遍感觉自己思路也没错,唯一的区别是柳神只用了一个数组来记录每个数字的位置,我除了这个数组外还有原来序列的本体。

完整代码

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<map>
#include<set>
#include<queue>
#include<string.h>

using namespace std;

void Swap(vector<int>& pos, int x) {
    int tmp = pos[x];
    pos[x] = pos[0];
    pos[0] = tmp;
}


int main() {
    int N;
    scanf("%d", &N);
    vector<int> pos(N);
    int cnt = 0;
    for (int i = 0; i < N; i++) {
        int num;
        scanf("%d", &num);
        pos[num] = i;
    }

    for (int i = 1; i < N; i++) {
        if (pos[i] != i) {
            while (pos[0] != 0) {
                Swap(pos, pos[0]);
                cnt++;
            }
            if (pos[i] != i) {
                Swap(pos, i);
                cnt++;
            }
        }
    }


    printf("%d", cnt);

    return 0;
}

之前超时的代码

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<map>
#include<set>
#include<queue>
#include<string.h>

using namespace std;

void Swap(vector<int>& arr, int x, int y){
    int tmp = arr[x];
    arr[x] = arr[y];
    arr[y] = tmp;
}

int main() {
    int N;
    scanf("%d", &N);
    vector<int> arr(N);
    vector<int> pos(N);
    vector<int> cpl;
    int cnt = 0;
    for (int i = 0; i < N; i++){
        scanf("%d", &arr[i]);
        pos[arr[i]] = i;
        if (i > 0 && arr[i] == i)
        		cpl.push_back(i);
    }
        
    
    while(cpl.size() < N-1){
        if (arr[0] != 0){
            int num = pos[0];
            int num_pos = find(arr.begin(), arr.end(), num);
            Swap(arr, num_pos, pos[0]);
            pos[num] = num;
            pos[0] = num_pos;
            cpl.push_back(num);
        }
        else{
            int num_pos = 1;
            while(arr[num_pos] == num_pos)
                num_pos++;
            int num = arr[num_pos];
            Swap(arr, num_pos, pos[0]);
            pos[num] = 0;
            pos[0] = num_pos;
        }
    }

    printf("%d", cnt);

    return 0;
}

先留着,以后在看看为什么超时。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值