You are given a sequence a1,a2,…,ana1,a2,…,an, consisting of integers.
You can apply the following operation to this sequence: choose some integer xx and move all elements equal to xxeither to the beginning, or to the end of aa. Note that you have to move all these elements in one direction in oneoperation.
For example, if a=[2,1,3,1,1,3,2]a=[2,1,3,1,1,3,2], you can get the following sequences in one operation (for convenience, denote elements equal to xx as xx-elements):
- [1,1,1,2,3,3,2][1,1,1,2,3,3,2] if you move all 11-elements to the beginning;
- [2,3,3,2,1,1,1][2,3,3,2,1,1,1] if you move all 11-elements to the end;
- [2,2,1,3,1,1,3][2,2,1,3,1,1,3] if you move all 22-elements to the beginning;
- [1,3,1,1,3,2,2][1,3,1,1,3,2,2] if you move all 22-elements to the end;
- [3,3,2,1,1,1,2][3,3,2,1,1,1,2] if you move all 33-elements to the beginning;
- [2,1,1,1,2,3,3][2,1,1,1,2,3,3] if you move all 33-elements to the end;
You have to determine the minimum number of such operations so that the sequence aa becomes sorted in non-descending order. Non-descending order means that for all ii from 22 to nn, the condition ai−1≤aiai−1≤ai is satisfied.
Note that you have to answer qq independent queries.
Input
The first line contains one integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of the queries. Each query is represented by two consecutive lines.
The first line of each query contains one integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of elements.
The second line of each query contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n) — the elements.
It is guaranteed that the sum of all nn does not exceed 3⋅1053⋅105.
Output
For each query print one integer — the minimum number of operation for sorting sequence aa in non-descending order.
Example
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
Note
In the first query, you can move all 11-elements to the beginning (after that sequence turn into [1,1,1,3,6,6,3][1,1,1,3,6,6,3]) and then move all 66-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 22-elements to the beginning.
将出现的数字种类和减去在整个过程中不移动的数字,就是最后的答案。
所以在做题的过程中只需要记录每一个数最开始出现的位置和最后出现的位置就好了。
#include<algorithm>
#include<iostream>
#include<map>
#include<queue>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<iostream>
#include<string>
using namespace std;
typedef long long ll;
const int maxn=3e5+100;
int l[maxn],r[maxn];
void init()
{
memset(l,0,sizeof(l));
memset(r,0,sizeof(r));
}
int main()
{
int T,x,n;
cin>>T;
while(T--)
{
// init();
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%d",&x);
if(!l[x])
{
l[x]=i;
}
r[x]=i;
}//计算每个点出现的最左边的位置和最右边的位置
int sum=0,ans_num=0,R=0,ret=0;
for(int i=1;i<=n;++i)
{
if(l[i])
{
sum++;
if(R<l[i])
{
ret++;//前面的比后面的小,说明是递增的
}
else
ret=1;//看做一个单独的数据
ans_num=max(ans_num,ret);
R=r[i];
}
}
printf("%d\n",sum-ans_num);
for(int i=0;i<=n;++i)
{
l[i]=r[i]=0;
}
}
return 0;
}