题目: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;
}
本文介绍了一种解决特定问题的算法:给定一个乱序序列,通过将元素移至序列开头的操作,使得序列变为增序,求最少操作次数。采用贪心策略,通过查找最大值位置并逆序寻找未排序元素,实现O(n)复杂度。
476

被折叠的 条评论
为什么被折叠?



