1792C.md (2238B)
1 Source: https://codeforces.com/problemset/problem/1792/C 2 3 C. Min Max Sort 4 5 time limit per test 6 7 2 seconds 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 You are given a permutation $p$ of length $n$ (a permutation of length $n$ is an array of length $n$ in which each integer from $1$ to $n$ occurs exactly once). 22 23 You can perform the following operation any number of times (possibly zero): 24 25 1. choose two different elements $x$ and $y$ and erase them from the permutation; 26 2. insert the minimum of $x$ and $y$ into the permutation in such a way that it becomes the first element; 27 3. insert the maximum of $x$ and $y$ into the permutation in such a way that it becomes the last element. 28 29 For example, if $p = [1, 5, 4, 2, 3]$ and we want to apply the operation to the elements $3$ and $5$, then after the first step of the operation, the permutation becomes $p = [1, 4, 2]$; and after we insert the elements, it becomes $p = [3, 1, 4, 2, 5]$. 30 31 Your task is to calculate the minimum number of operations described above to sort the permutation $p$ in ascending order (i. e. transform $p$ so that $p_1 \lt p_2 \lt \dots \lt p_n$). 32 33 Input 34 35 The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. 36 37 The first line of the test case contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in the permutation. 38 39 The second line of the test case contains $n$ distinct integers from $1$ to $n$ — the given permutation $p$. 40 41 The sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$. 42 43 Output 44 45 For each test case, output a single integer — the minimum number of operations described above to sort the array $p$ in ascending order. 46 47 Example 48 49 Input 50 51 ``` 52 4 53 54 5 55 56 1 5 4 2 3 57 58 3 59 60 1 2 3 61 62 4 63 64 2 1 4 3 65 66 6 67 68 5 2 4 1 6 3 69 ``` 70 71 Output 72 73 ``` 74 2 75 0 76 1 77 3 78 ``` 79 80 Note 81 82 In the first example, you can proceed as follows: 83 84 1. in the permutation $p = [1, 5, 4, 2, 3]$, let's choose the elements $4$ and $2$, then, after applying the operation, the permutation becomes $p = [2, 1, 5, 3, 4]$; 85 2. in the permutation $p = [2, 1, 5, 3, 4]$, let's choose the elements $1$ and $5$, then, after applying operation, the permutation becomes $p = [1, 2, 3, 4, 5]$.