Sequence in the Pocket(2019浙江省省賽)(找規律)

Sequence in the Pocket(2019浙江省省賽)(找規律)

Time Limit: 2000 ms
Memory Limit: 65536 KB
judge:
ZOJ
vjudge

Description

DreamGrid has just found an integer sequence a1,a2,,ana_1, a_2, \dots, a_n 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 TT, indicating the number of test cases. For each test case:

The first line contains an integer nn (1n1051 \le n \le 10^5), indicating the length of the sequence.

The second line contains nn integers a1,a2,,ana_1, a_2, \dots, a_n (1ai1091 \le a_i \le 10^9), indicating the given sequence.

It’s guaranteed that the sum of nn of all test cases will not exceed 10610^6.

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章