#P15178. [SWERC 2021] Round Table

[SWERC 2021] Round Table

题目描述

There are n n people, numbered from 1 1 to n n , sitting at a round table. Person i+1 i+1 is sitting to the right of person i i (with person 1 1 sitting to the right of person n n ).

You have come up with a better seating arrangement, which is given as a permutation p1,p2,,pn p_1, p_2, \dots, p_n . More specifically, you want to change the seats of the people so that at the end person pi+1 p_{i+1} is sitting to the right of person pi p_i (with person p1 p_1 sitting to the right of person pn p_n ). Notice that for each seating arrangement there are n n permutations that describe it (which can be obtained by rotations).

In order to achieve that, you can swap two people sitting at adjacent places; but there is a catch: for all 1xn1 1 \le x \le n-1 you cannot swap person x x and person x+1 x+1 (notice that you can swap person n n and person 1 1 ). What is the minimum number of swaps necessary? It can be proven that any arrangement can be achieved.

输入格式

Each test contains multiple test cases. The first line contains an integer t t ( 1t10000 1\le t\le 10\,000 ) — the number of test cases. The descriptions of the t t test cases follow.

The first line of each test case contains a single integer n n ( 3n200000 3 \le n \le 200\,000 ) — the number of people sitting at the table.

The second line contains n n distinct integers p1,p2,,pn p_1, p_2, \dots, p_n ( 1pin 1 \le p_i \le n , pipj p_i \ne p_j for ij i \ne j ) — the desired final order of the people around the table.

The sum of the values of n n over all test cases does not exceed 200000 200\,000 .

输出格式

For each test case, print the minimum number of swaps necessary to achieve the desired order.

3
4
2 3 1 4
5
5 4 3 2 1
7
4 1 6 5 3 7 2
1
10
22

提示

In the first test case, we can swap person 4 4 and person 1 1 (who are adjacent) in the initial configuration and get the order [4,2,3,1] [4, 2, 3, 1] which is equivalent to the desired one. Hence in this case a single swap is sufficient.