https://codeforces.com/contest/1241/problem/D
You are given a sequence a1,a2,…,an, consisting of integers.
You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation.
For example, if a=[2,1,3,1,1,3,2], you can get the following sequences in one operation (for convenience, denote elements equal to x as x-elements):
You have to determine the minimum number of such operations so that the sequence a becomes sorted in non-descending order. Non-descending order means that for all i from 2 to n, the condition ai−1≤ai is satisfied.
Note that you have to answer q independent queries.
Input
The first line contains one integer q (1≤q≤3⋅10^5) — the number of the queries. Each query is represented by two consecutive lines.
The first line of each query contains one integer n (1≤n≤3⋅10^5) — the number of elements.
The second line of each query contains n integers a1,a2,…,an (1≤ai≤n) — the elements.
It is guaranteed that the sum of all nn does not exceed 3⋅10^5.
Output
For each query print one integer — the minimum number of operation for sorting sequence aa in non-descending order.
input
3
7
3 1 6 6 3 1 1
8
1 1 4 4 4 7 8 8
7
4 2 5 2 6 2 7
output
2
0
1
In the first query, you can move all 1-elements to the beginning (after that sequence turn into [1,1,1,3,6,6,3]) and then move all 6-elements to the end.
In the second query, the sequence is sorted initially, so the answer is zero.
In the third query, you have to move all 2-elements to the beginning.
这题从正面想难度很大,基本上是无解。
我们可以将所有数分为两类,一类需要移动才能将整个序列排为有序,另一类原地不动即可。
可以看出,对那些需要移动的数,只需移动一次即可使数字就位。
那么只需求出最多有多少种数字可以原地不动就行了。
这样这道题难度就不大了。
#include<bits/stdc++.h>
#define ll long long
#define maxn 300010
using namespace std;
void read(ll &x){
ll f=1;x=0;char s=getchar();
while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
x*=f;
}
ll t,n,f[maxn],ns[maxn];
ll a[maxn],l[maxn],r[maxn];
vector<ll>st;
int main(){
read(t);
ll i;
while(t--){
read(n);
for(i=1;i<=n;i++)read(a[i]);
st.clear();
for(i=0;i<=n+1;i++){
f[i]=0;
l[i]=0;
r[i]=0;
ns[i]=0;
}
for(i=1;i<=n;i++){
if(!l[a[i]]){
l[a[i]]=i;
r[a[i]]=i;
//st.push_back(a[i]);
}
else{
l[a[i]]=min(l[a[i]],i);
r[a[i]]=max(r[a[i]],i);
}
}
ll be=0;
for(i=1;i<=n;i++){
if(l[i]){
st.push_back(i);
ns[i]=be;
be=i;
}
}
f[st[0]]=1;
for(i=1;i<st.size();i++){
int v=st[i],u=st[i-1];
f[v]=1;
if(u==ns[v]&&l[v]>r[u])f[v]=f[u]+1;
}
ll ans=0;
for(i=1;i<=n;i++){
ans=max(f[i],ans);
}
cout<<st.size()-ans<<endl;
}
return 0;
}