Link:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1241
一个数组的元素为1至N的整数,现在要对这个数组进行排序,在排序时只能将元素放在数组的头部或尾部,问至少需要移动多少个数字,才能完成整个排序过程?
例如:
2 5 3 4 1 将1移到头部 =>
1 2 5 3 4 将5移到尾部 =>
1 2 3 4 5 这样就排好了,移动了2个元素。
给出一个1-N的排列,输出完成排序所需的最少移动次数。
Input
第1行:1个数N(2 <= N <= 50000)。 第2 - N + 1行:每行1个数,对应排列中的元素。
Output
输出1个数,对应所需的最少移动次数。
Input示例
5 2 5 3 4 1
Output示例
2
AC code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int N,x,ans,maxlen;
int dp[1000010];
int main()
{
int i;
while(scanf("%d",&N)!=EOF)
{
memset(dp,0,sizeof(dp));
ans=0;
maxlen=0;
for(i=1;i<=N;i++)
{
scanf("%d",&x);
dp[x]=dp[x-1]+1;
maxlen=max(maxlen,dp[x]);
}
ans=N-maxlen;
printf("%d\n",ans);
}
return 0;
}

168万+

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



