[Codeforces 606C]Sorting Railway Cars

Description

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 Input

5
4 1 2 5 3

Sample Output

2

Hint

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.

题解

首先容易注意到答案一定不会超过 $n$,因为我们只要按照大小顺序每个数都移动一次,整个序列就一定有序了,由以上结论还可以得每个数至多被移动一次。

由于操作是将数移动到序列首部和序列尾部,那么没有被移动的数会停留在序列中部,所以这些数一定是原序列的一个子序列,并且是有序序列的一个连续子段。最小化移动即是最大化不动,那么我们找到最长的这样的一个子序列就行了。

时间复杂度 $O(n)$ 。

 1 //It is made by Awson on 2017.10.17
 2 #include <set>
 3 #include <map>
 4 #include <cmath>
 5 #include <ctime>
 6 #include <queue>
 7 #include <stack>
 8 #include <vector>
 9 #include <cstdio>
10 #include <string>
11 #include <cstdlib>
12 #include <cstring>
13 #include <iostream>
14 #include <algorithm>
15 #define LL long long
16 #define Max(a, b) ((a) > (b) ? (a) : (b))
17 #define Min(a, b) ((a) < (b) ? (a) : (b))
18 using namespace std;
19 const int N = 200000;
20 void read(int &x) {
21   char ch = getchar(); x = 0;
22   while (ch < '0' || ch > '9') ch = getchar();
23   while (ch >= '0' && ch <= '9') x = (x<<1)+(x<<3)+ch-48, ch = getchar();
24 }
25 
26 int n, ans, a;
27 int f[N+5];
28 
29 void work() {
30   read(n);
31   for (int i = 1; i <= n; i++) {
32     read(a); f[a] = f[a-1]+1;
33     ans = Max(ans, f[a]);
34   }
35   printf("%d\n", n-ans);
36 }
37 int main() {
38   work();
39   return 0;
40 }

 

转载于:https://www.cnblogs.com/NaVi-Awson/p/7681131.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值