Codeforces 335C 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?
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.
Print a single integer — the minimum number of actions needed to sort the railway cars.
5
4 1 2 5 3
2
4
4 1 3 2
2
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的左边还是右边
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#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 = 100005; 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 = 1; i <= n; ++i) scanf("%d", &a[i]); for(int i = 1; i <= n; ++i) r[i] = i; sort(r + 1, r + n + 1, cmp); d[1] = 1; for(int i = 1; i < n; ++i) { if(r[i] < r[i + 1]) d[i + 1] = 1; else d[i + 1] = 0; } dp[ r[1] ] = 1; int ans = 1; for(int i = 2; i <= n; ++i) { if(d[i]) dp[ r[i] ] = dp[ r[i-1] ] + 1; else dp[ r[i] ] = 1; ans = max(ans, dp[ r[i] ]); } printf("%d\n", n - ans); return 0; }