题目链接
Sequence in the Pocket
Time Limit: 2 Seconds Memory Limit: 65536 KB
DreamGrid has just found an integer sequence a1,a2,…,an in his right pocket. As DreamGrid is bored, he decides to play with the sequence. He can perform the following operation any number of times (including zero time): select an element and move it to the beginning of the sequence.
What's the minimum number of operations needed to make the sequence non-decreasing?
Input
There are multiple test cases. The first line of the input contains an integer T, indicating the number of test cases. For each test case:
The first line contains an integer n (1≤n≤105), indicating the length of the sequence.
The second line contains n integers a1,a2,…,an (1≤ai≤109), indicating the given sequence.
It's guaranteed that the sum of n of all test cases will not exceed 106.
Output
For each test case output one line containing one integer, indicating the answer.
Sample Input
2 4 1 3 2 4 5 2 3 3 5 5
Sample Output
2 0
Hint
For the first sample test case, move the 3rd element to the front (so the sequence become {2, 1, 3, 4}), then move the 2nd element to the front (so the sequence become {1, 2, 3, 4}). Now the sequence is non-decreasing.
For the second sample test case, as the sequence is already sorted, no operation is needed.
题解:从后往前维护一个最大的递减子序列就行了
例如样例
4
1 3 2 4
用一个b数组存下并排序,得到 1 2 3 4,在原序列里找最大的4此时sum=1,然后往前找3此时sum=2,然后往前找2,发现找不到,于是用总长度n-sum就是答案了。
例如样例
6
2 3 1 4 7 6
先找到7此时sum=1,于是往前找6,发现找不到于是用 n-sum=5就是答案了
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+6;
int a[maxn];
int b[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
int n;
int ans=0;
scanf("%d",&n);
int maxn=-1;
int maxn1=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
b[i]=a[i];
if(a[i]>=maxn)
{
maxn1=i;
maxn=a[i];
}
}
sort(b,b+n);
int sum=1;
int j=n-2;//直接从倒数第二个开始找
for(int i=maxn1-1;i>=0;i--)
{
if(a[i]==b[j])
{
j--;
sum++;
}
}
ans=n-maxn1-1;
printf("%d\n",n-sum);
}
}