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 3 2 4 5 , 可以看出这段数的最长连续数的个数是 3 个 , 因此递推的状态转移方程是 dp[pre[i]] = dp[pre[ i ] - 1] + 1;
代码示例 :
/* * Author: ry * Created Time: 2017/9/28 14:25:17 * File Name: 1.cpp */#include#include #include #include #include #include #include #include #include #include #include #include using namespace std;const int eps = 1e5+5;const double pi = acos(-1.0);#define Max(a,b) a>b?a:b#define Min(a,b) a>b?b:a#define ll long longint pre[eps];int dp[eps];int main() { int n; while (~scanf("%d", &n)){ memset(dp, 0, sizeof(dp)); for(int i = 1; i <= n; i++){ scanf("%d", pre+i); } for(int i = 1; i <= n; i++) dp[pre[i]] = dp[pre[i]-1] + 1; printf("%d\n", n - *max_element(dp+1, dp+1+n)); } return 0;}
/* * Author: ry * Created Time: 2017/9/28 14:25:17 * File Name: 1.cpp */#include#include #include #include #include #include #include #include #include #include #include #include using namespace std;const int eps = 1e5+5;const double pi = acos(-1.0);#define Max(a,b) a>b?a:b#define Min(a,b) a>b?b:a#define ll long longint pre[eps];int dp[eps];int main() { int n; while (~scanf("%d", &n)){ memset(dp, 0, sizeof(dp)); for(int i = 1; i <= n; i++){ scanf("%d", pre+i); } for(int i = 1; i <= n; i++) dp[pre[i]] = dp[pre[i]-1] + 1; printf("%d\n", n - *max_element(dp+1, dp+1+n)); } retu