Codeforces 335C Sorting Railway Cars

时间:2023-03-08 17:58:25
time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

Input

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.

The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Output

Print a single integer — the minimum number of actions needed to sort the railway cars.

Sample test(s)
Input
5
4 1 2 5 3
Output
2
Input
4
4 1 3 2
Output
2
Note

In the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

题意:给你一个1~n的一个排列,一次操作是指把选一个数移动到头或尾,求使序列递增的最小操作数

思路:我们需要找一个最长的递增子序列b1,b2,b3..bm,且该子序列要满足bm = bm-1 + 1. 比如4 1 2 5 3  满足的最长递增子序列是1 2 3,那么答案最终是n -m

即我们找到这样的一个子序列后,对于其他的数,只要从小到达移到到该子序列的两端即可

r[i]表示第i大的元素,d[i]表示比i小1的数在i的左边还是右边

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <map>
#include <set>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long ll;
const int N = ;
int dp[N], a[N], d[N], r[N];
int cmp(int b, int c) {
return a[b] < a[c];
}
int main()
{
int n;
scanf("%d", &n);
for(int i = ; i <= n; ++i) scanf("%d", &a[i]);
for(int i = ; i <= n; ++i) r[i] = i;
sort(r + , r + n + , cmp);
d[] = ;
for(int i = ; i < n; ++i)
{
if(r[i] < r[i + ]) d[i + ] = ;
else d[i + ] = ;
}
dp[ r[] ] = ;
int ans = ;
for(int i = ; i <= n; ++i)
{
if(d[i]) dp[ r[i] ] = dp[ r[i-] ] + ;
else dp[ r[i] ] = ;
ans = max(ans, dp[ r[i] ]);
}
printf("%d\n", n - ans);
return ;
}