CF BUDDY
← Problems·

1792C · Min Max Sort

1500 · binary search, brute force, greedy

Problem: You are given a permutation pp of length nn (a permutation of length nn is an array of length nn in which each integer from 11 to nn occurs exactly once).

You can perform the following operation any number of times (possibly zero):

  1. choose two different elements xx and yy and erase them from the permutation;
  2. insert the minimum of xx and yy into the permutation in such a way that it becomes the first element;
  3. insert the maximum of xx and yy into the permutation in such a way that it becomes the last element.

For example, if p=[1,5,4,2,3]p = [1, 5, 4, 2, 3] and we want to apply the operation to the elements 33 and 55, then after the first step of the operation, the permutation becomes p=[1,4,2]p = [1, 4, 2]; and after we insert the elements, it becomes p=[3,1,4,2,5]p = [3, 1, 4, 2, 5].

Your task is to calculate the minimum number of operations described above to sort the permutation pp in ascending order (i. e. transform pp so that p1<p2<<pnp_1 < p_2 < \dots < p_n).

Input Format: The first line contains a single integer tt (1t1041 \le t \le 10^4) — the number of test cases.

The first line of the test case contains a single integer nn (1n21051 \le n \le 2 \cdot 10^5) — the number of elements in the permutation.

The second line of the test case contains nn distinct integers from 11 to nn — the given permutation pp.

The sum of nn over all test cases doesn't exceed 21052 \cdot 10^5.

Output Format: For each test case, output a single integer — the minimum number of operations described above to sort the array pp in ascending order.

Note: In the first example, you can proceed as follows:

  1. in the permutation p=[1,5,4,2,3]p = [1, 5, 4, 2, 3], let's choose the elements 44 and 22, then, after applying the operation, the permutation becomes p=[2,1,5,3,4]p = [2, 1, 5, 3, 4];
  2. in the permutation p=[2,1,5,3,4]p = [2, 1, 5, 3, 4], let's choose the elements 11 and 55, then, after applying operation, the permutation becomes p=[1,2,3,4,5]p = [1, 2, 3, 4, 5].

Sample Cases

Case 1

Input

4
5
1 5 4 2 3
3
1 2 3
4
2 1 4 3
6
5 2 4 1 6 3

Output

2
0
1
3

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback