[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 }
[Codeforces 606C]Sorting Railway Cars