天天看點

Sequence in the Pocket【思維+規律】

Sequence in the Pocket

題目連結(點選)

DreamGrid has just found an integer sequence  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 , indicating the number of test cases. For each test case:

The first line contains an integer  (), indicating the length of the sequence.

The second line contains  integers  (), indicating the given sequence.

It's guaranteed that the sum of  of all test cases will not exceed .

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.

題意:

給出T組  每組一個序列 每次操作可以把其中的一個數移動到最前方 需要幾次操作可以将序列變成從小到大

思路:

将序列從小到大排序 然後将新的序列從後往前每次枚舉一個值 在原序列中查找出來num個  是以需要移動的次數是n-num

例如:

1 2 3 1 2 3 排序後是 1 1 2 2 3 3

依次枚舉3 3 2 2  1 1  

3 可以找到  j=n-1 時

3可以找到   j=n-4時

2可以找到   j=n-5時

在枚舉第二個2的時候 就找不到了(j一直在減小)  

代碼:

#include<stdio.h>
#include<algorithm>
using namespace std;
const int MAX=1e5;
int main()
{
    int a[MAX+5],b[MAX+5],T;
    scanf("%d",&T);
    while(T--){
        int n;
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%d",&a[i]);
            b[i]=a[i];
        }
        sort(b,b+n);
        int j=n-1,num=0;
        for(int i=n-1;i>=0;i--){  ///for+while 這種寫法很好 
            while(b[i]!=a[j]&&j>=0){
                j--;
            }
            if(j<0){
                break;
            }
            else{
                num++;
                j--;
                //printf("%d ",b[i]);
            }
        }
       // printf("\n");
        printf("%d\n",n-num);
    }
    return 0;
}
           

繼續閱讀