1863B.md (2673B)
1 Source: https://codeforces.com/problemset/problem/1863/B 2 3 B. Split Sort 4 5 time limit per test 6 7 1 second 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$^{\dagger}$ $p_1, p_2, \ldots, p_n$ of integers $1$ to $n$. 22 23 You can change the current permutation by applying the following operation several (possibly, zero) times: 24 25 * choose some $x$ ($2 \le x \le n$); 26 * create a new permutation by: 27 + first, writing down all elements of $p$ that are less than $x$, without changing their order; 28 + second, writing down all elements of $p$ that are greater than or equal to $x$, without changing their order; 29 * replace $p$ with the newly created permutation. 30 31 For example, if the permutation used to be $[6, 4, 3, 5, 2, 1]$ and you choose $x = 4$, then you will first write down $[3, 2, 1]$, then append this with $[6, 4, 5]$. So the initial permutation will be replaced by $[3, 2, 1, 6, 4, 5]$. 32 33 Find the minimum number of operations you need to achieve $p_i = i$ for $i = 1, 2, \ldots, n$. We can show that it is always possible to do so. 34 35 $^{\dagger}$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). 36 37 Input 38 39 Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 1000$). The description of the test cases follows. 40 41 The first line of each test case contains one integer $n$ ($1 \le n \le 100\,000$). 42 43 The second line of each test case contains $n$ integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$). It is guaranteed that $p_1, p_2, \ldots, p_n$ is a permutation. 44 45 It is guaranteed that the sum of $n$ over all test cases does not exceed $100\,000$. 46 47 Output 48 49 For each test case, output the answer on a separate line. 50 51 Example 52 53 Input 54 55 ``` 56 5 57 58 1 59 60 1 61 62 2 63 64 2 1 65 66 6 67 68 6 4 3 5 2 1 69 70 3 71 72 3 1 2 73 74 19 75 76 10 19 7 1 17 11 8 5 12 9 4 18 14 2 6 15 3 16 13 77 ``` 78 79 Output 80 81 ``` 82 0 83 1 84 4 85 1 86 7 87 ``` 88 89 Note 90 91 In the first test case, $n = 1$ and $p_1 = 1$, so there is nothing left to do. 92 93 In the second test case, we can choose $x = 2$ and we immediately obtain $p_1 = 1$, $p_2 = 2$. 94 95 In the third test case, we can achieve the minimum number of operations in the following way: 96 97 1. $x = 4$: $[6, 4, 3, 5, 2, 1] \rightarrow [3, 2, 1, 6, 4, 5]$; 98 2. $x = 6$: $[3, 2, 1, 6, 4, 5] \rightarrow [3, 2, 1, 4, 5, 6]$; 99 3. $x = 3$: $[3, 2, 1, 4, 5, 6] \rightarrow [2, 1, 3, 4, 5, 6]$; 100 4. $x = 2$: $[2, 1, 3, 4, 5, 6] \rightarrow [1, 2, 3, 4, 5, 6]$.