一个数组的元素为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
这期codeforces的原题。
因为可以把一个数向最前面移或者是最后面移,即把不符合排序的那些数拿走,所以求的就是n-最长递增序列的长度。
代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std;
long long n, x, maxn, temp;
long long dp[50005];
int main()
{
//freopen("i.txt","r",stdin);
//freopen("o.txt","w",stdout);
maxn = -1;
memset(dp, 0, sizeof(dp));
cin >> n;
temp = n;
while (temp--)
{
cin >> x;
dp[x] = dp[x - 1] + 1;
maxn = max(dp[x], maxn);
}
cout << n - maxn << endl;
return 0;
}