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.
题意:给n长度的序列,每次能把任意位置的数移到序列头,序列尾算一个操作,问你最少经过几次操作使其有序;
题解:也就是最长连续子序列
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
//meek ///#include<bits/stdc++.h> #include <iostream> #include <cstdio> #include <cmath> #include <string> #include <cstring> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <sstream> #include <vector> using namespace std ; typedef long long ll; #define mem(a) memset(a,0,sizeof(a)) #define pb push_back #define fi first #define se second #define MP make_pair inline ll read() { ll x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9') { if(ch=='-')f=-1; ch=getchar(); } while(ch>='0'&&ch<='9') { x=x*10+ch-'0'; ch=getchar(); } return x*f; } //**************************************** const int N=100000+100; const ll inf = 1ll<<61; const int mod= 1000000007; int ans,a[N],H[N],n; int dp[N]; int main() { ans=-1; scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); } for(int i=1;i<=n;i++) { H[a[i]] ++; if(H[a[i]-1]) dp[a[i]]=dp[a[i]-1]+1; else dp[a[i]]=1; ans=max(ans,dp[a[i]]); } cout<<n-ans<<endl; return 0;