codeforces 606C Sorting Railway Cars

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?

一个无限长的铁路有一个载着n辆车的火车,每一辆车的编号从1到n。每一辆车的编号都是不同的。他们的顺序是无序的。
David Blaine想要将这些车按照他们的编号从小到大排序,他可以做两种操作。第一种,他可以将一辆车从任意位置移动到所有车的第一位。第二种,他可以将一辆车从任意位置移动到所有车的最后一位。
不过他很懒,所以他想知道将这些车排好序最少做几次操作就可以。

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.

Examples
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.

首先容易注意到答案一定不会超过 n ,因为我们只要按照大小顺序每个数都移动一次,整
个序列就一定有序了,由以上结论还可以得每个数至多被移动一次。
由于操作是将数移动到序列首部和序列尾部,那么没有被移动的数会停留在序列中部,所
以这些数一定是原序列的一个子序列,并且是有序序列的一个连续子段。最小化移动即是
最大化不动,那么我们找到最长的这样的一个子序列就行了。
这个问题应该有很多做法,具体参见代码。
时间复杂度 O(n) 。

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 int n,a[100001],f[100001],c[100001],ans;
 7 int main()
 8 {int i;
 9   cin>>n;
10   for (i=1;i<=n;i++)
11     scanf("%d",&a[i]);
12   for (i=1;i<=n;i++)
13     {
14       f[i]=f[c[a[i]-1]]+1;
15       c[a[i]]=i;
16       ans=max(ans,f[i]);
17     }
18   cout<<n-ans;
19 }

 

 

 

posted @ 2017-10-17 14:34  Z-Y-Y-S  阅读(240)  评论(0编辑  收藏  举报