P22403 [CodeChef] COOKPERM
提高+
题目描述

Chef is bored cooking his regular dishes, so he decided to cook permutations instead. Since this is his first time cooking permutations, he takes some help.

Chef has two permutations A and B, each of size N. Chef cooks a permutation C of size N^{2} by doing the following:

for i = 1 to N:
for j = 1 to N:
C[i + (j-1) * N] = A[i] + (B[j] - 1) * N

Chef is allowed to make some (maybe 0) moves on permutation C. In one move, Chef can:
Pick two indices 1 ≤ i < j ≤ N^{2} and swap the elements C_{i} and C_{j}.

Find the minimum number of moves required to sort permutation C in ascending order.

------ Input Format ------

  • The first line of the input contains a single integer T - the number of test cases. The description of test cases follows.
  • The first line of each test case contains an integer N - the length of permutations A and B.
  • The second line of each test case contains $N integers A_{1}, A_{2}, \ldots, A_{N}, denoting permutation A$.
  • The third line of each test case contains $N integers B_{1}, B_{2}, \ldots, B_{N}, denoting permutation B$.

------ Output Format ------

For each test case, print a single integer representing the number of moves required to sort permutation C.

------ Constraints ------

$1 ≤T ≤10^{5}$
$1 ≤N ≤2 \cdot 10^{5}$
$1 ≤A_{i}, B_{i} ≤N$
- The sum of $N$ over all test cases doesn't exceed $10^{6}$

------ subtasks ------

Subtask #1 (100 points): original constraints

----- Sample Input 1 ------
3
3
3 1 2
2 1 3
2
1 2
1 2
2
2 1
2 1

----- Sample Output 1 ------
7
0
2
----- explanation 1 ------
- In the first test case, $C = [6, 4, 5, 3, 1, 2, 9, 7, 8]$. Minimum number of moves required to sort permutation $C$ are $7$.
- In the second test case, $C = [1, 2, 3, 4]$. The permutation is already sorted, so we need $0$ moves.
- In the third test case, $C = [4, 3, 2, 1]$. We need $2$ moves to sort the permutation.

输入格式

见题面

输出格式

见题面

样例输入
3 3 3 1 2 2 1 3 2 1 2 1 2 2 2 1 2 1
样例输出
7 0 2