码迷,mamicode.com
首页 > 其他好文 > 详细

[Codeforces 606C]Sorting Railway Cars

时间:2017-10-25 21:26:18      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:cst   long   lib   one   make   最小   efi   nbsp   子序列   

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 }

 

[Codeforces 606C]Sorting Railway Cars

标签:cst   long   lib   one   make   最小   efi   nbsp   子序列   

原文地址:http://www.cnblogs.com/NaVi-Awson/p/7681131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!