有趣的排序 (贪心+思维)

题意:度度熊有一个N个数的数组,他想将数组从小到大 排好序,但是萌萌的度度熊只会下面这个操作:
任取数组中的一个数然后将它放置在数组的最后一个位置。
问最少操作多少次可以使得数组从小到大有序?
注意:题目中没有说明每个数是否唯一,我把它当做唯一的AC了。说明n个数中没有重复的!


思路:以前在hihoCoder做过类似的题。设 pos(i) 表示数字 i 当前所在的位置,假设我们将数组A排序,那么如果 A[i]<A[i+1] 那么应该满足 pos[A[i]]<pos[A[i+1]] ,假如原数组中存在 pos[A[i]]>pos[A[i+1]] ,就应该把 A[i] 移动到最后。


AC代码

#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn = 1000+5;
const int pour = 1000;
int a[50+5], pos[maxn<<1];
int main() {
    int n;
    while(scanf("%d", &n) == 1) {
        for(int i = 0; i < n; i++) {
            scanf("%d", &a[i]);
            a[i] += pour;
            pos[a[i]] = i;
        }
        sort(a, a+n);
        int now = n, tol = 0;
        for(int i = 1; i < n; i++) {
            int l = a[i-1];
            if(pos[l] > pos[a[i]]) {
                pos[a[i]] = now++;
                tol++;
            }
        }
        printf("%d\n", tol);
    }
    return 0;
}

如有不当之处欢迎指出!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值