hdu 5500 Reorder the books

题目:http://acm.hdu.edu.cn/showproblem.php?pid=5500

给定一个从1到n的乱序序列,每次取一个数到最前面,问最少多少次能使序列变为增序。

初始以为是逆序数,后来知道不对,应该是贪心。

细想发现,加入操作了大小等于k的数,那么所有小于k的数也都得操作。首先最大的数n是不用操作的(其他数操作好了,n自然在最后面了)。先找到数n的位置,在n之前找n-1,若没找到n-1,则n-1需要操作,所有小于n-1的数均需要操作;若找到了n-1,再接着往前依次找n-2,n-3,。。。假如数k找不到了,那就是至少需要k次操作。

复杂度O(n)。

#include<cstdio>
#include<cstdlib>
#include<vector>
#include<cstring>
#include<set>
#include<queue>
#include<stack>
#include<map>
#include<algorithm>
#include<iostream>
#include<ctime>
#include<bitset>
using namespace std;
#define N 300005
#define NMAX 2000000000 
typedef long long ll;

int a[22];
bool cmp(const int& x, const int& y){
    return x>y;
}

int main(){
    int T, n, m;
    while ( scanf("%d", &T) != EOF){
        while ( T > 0 ){
            T--;
            scanf("%d", &n);
            int index = -1;
            for ( int i = 0 ;i < n; i++ ){
                scanf("%d", &a[i]);
            }
            int ans = 0, t = n - 1, cur = n;
            while ( t >= 0 ){
                if ( a[t] == cur ) cur--;
                t--;
            }
            cout << cur << endl;
        }
    } 
    return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值