310851: CF1899E. Queue Sort

Memory Limit:256 MB Time Limit:1 S
Judge Style:Text Compare Creator:
Submit:5 Solved:0

Description

E. Queue Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output

Vlad found an array $a$ of $n$ integers and decided to sort it in non-decreasing order.

To do this, Vlad can apply the following operation any number of times:

  • Extract the first element of the array and insert it at the end;
  • Swap that element with the previous one until it becomes the first or until it becomes strictly greater than the previous one.

Note that both actions are part of the operation, and for one operation, you must apply both actions.

For example, if you apply the operation to the array [$4, 3, 1, 2, 6, 4$], it will change as follows:

  • [$\color{red}{4}, 3, 1, 2, 6, 4$];
  • [$3, 1, 2, 6, 4, \color{red}{4}$];
  • [$3, 1, 2, 6, \color{red}{4}, 4$];
  • [$3, 1, 2, \color{red}{4}, 6, 4$].

Vlad doesn't have time to perform all the operations, so he asks you to determine the minimum number of operations required to sort the array or report that it is impossible.

Input

The first line of the input contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Descriptions of the test cases follow.

The first line of each test case contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the array.

The second line of each test case contains $n$ integers $a_1, a_2, a_3, \dots, a_n$ ($1 \le a_i \le 10^9$) — the elements of the array.

It is guaranteed that the sum of $n$ over all testcases does not exceed $2 \cdot 10^5$.

Output

For each test case, output a single integer — the minimum number of operations needed to sort the array. If it is impossible to do so, output $-1$ as the answer.

ExampleInput
5
5
6 4 1 2 5
7
4 5 3 7 8 6 2
6
4 3 1 2 6 4
4
5 2 4 2
3
2 2 3
Output
2
6
-1
-1
0

Output

题目大意:
Vlad找到了一个包含n个整数的数组a,并决定将其按非递减顺序排序。

为了做到这一点,Vlad可以任意次数地应用以下操作:
1. 提取数组的第一个元素并将其插入到末尾;
2. 将该元素与前面的元素交换,直到它成为第一个元素或者直到它严格大于前一个元素。

注意,这两个动作都是操作的一部分,对于一个操作,必须同时应用这两个动作。

输入输出数据格式:
输入:
第一行包含一个整数t(1≤t≤10^4)——测试用例的数量。接下来是t个测试用例的描述。
每个测试用例的第一行包含一个整数n(1≤n≤2×10^5)——数组的长度。
每个测试用例的第二行包含n个整数a1,a2,a3,…,an(1≤ai≤10^9)——数组的元素。
保证所有测试用例的n之和不超过2×10^5。

输出:
对于每个测试用例,输出一个整数——将数组排序所需的最小操作数。如果无法完成排序,则输出-1作为答案。题目大意: Vlad找到了一个包含n个整数的数组a,并决定将其按非递减顺序排序。 为了做到这一点,Vlad可以任意次数地应用以下操作: 1. 提取数组的第一个元素并将其插入到末尾; 2. 将该元素与前面的元素交换,直到它成为第一个元素或者直到它严格大于前一个元素。 注意,这两个动作都是操作的一部分,对于一个操作,必须同时应用这两个动作。 输入输出数据格式: 输入: 第一行包含一个整数t(1≤t≤10^4)——测试用例的数量。接下来是t个测试用例的描述。 每个测试用例的第一行包含一个整数n(1≤n≤2×10^5)——数组的长度。 每个测试用例的第二行包含n个整数a1,a2,a3,…,an(1≤ai≤10^9)——数组的元素。 保证所有测试用例的n之和不超过2×10^5。 输出: 对于每个测试用例,输出一个整数——将数组排序所需的最小操作数。如果无法完成排序,则输出-1作为答案。

加入题单

上一题 下一题 算法标签: