Sequence in the Pocket(2019浙江省省賽)(找規律)
Time Limit: 2000 ms
Memory Limit: 65536 KB
judge:
ZOJ
vjudge
Description
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.
題意
給你一個序列,你可以選擇一個數字然後他會被放到序列的最前面,你可以執行任意次此操作,問你把這個序列變爲非遞減的序列最少需要多少步操作。
題解
加入有一個序列:
那麼它變爲非遞減的序列後應該是這樣子:
想一下中間哪些數字沒有被操作?
應該是這幾個:
因爲他們沒必要被操作。
仔細觀察發現這三個數從右往左看,是依次遞減的,而且他們的相對位置在最終的序列中也是這個樣子。那就不難想到答案就是序列的長度減去已經排好位置的最大的數字的個數。
代碼
#include <bits/stdc++.h>
#define maxn 100005
#define _for(i, a) for(int i = 0; i < (a); ++i)
#define sc(x) scanf("%d", &x)
using namespace std;
int T, n, a[maxn], ans, b[maxn];
void sol() {
ans = 0;
_for(i, n) sc(a[i]), b[i] = a[i];
sort(b, b + n);
int p = n - 1;
for (int i = n - 1; i >= 0; --i) if (a[i] == b[p]) --p;
printf("%d\n", p + 1);
}
int main() {
while (cin >> T) {
_for(i, T) {
sc(n);
sol();
}
}
return 0;
}