Under construction

Still being built. Things may change

Reachable Sequences

Time limit4sMemory limit512 MB

Summary
Count ordered pairs of permutations (i, j) where a^(i) can be reached from a^(j) by repeatedly swapping an out-of-order pair.
Level

Hard8 of 10

Topics
Combinatorics, Bit manipulation, Array
Solved
No attempts yet

Problem

ZZX has a sequence aa, which is a permutation of 1,2,…,n1, 2, \ldots, n. ZZX wants to modify this sequence. In one modification, he chooses a pair of integers ii and jj with 1≤i<j≤n1 \le i < j \le n and ai>aja_i > a_j, then swaps aia_i and aja_j.

If a permutation bb can be obtained from the initial sequence aa by performing some (possibly zero) modifications, then ZZX says bb is reachable from aa.

JRY has mm sequences a(1),a(2),…,a(m)a^{(1)}, a^{(2)}, \ldots, a^{(m)}. Each of them is a permutation of 1,2,…,n1, 2, \ldots, n. He wants to know how many pairs (i,j)(i, j) with 1≤i≤m1 \le i \le m and 1≤j≤m1 \le j \le m satisfy that a(i)a^{(i)} is reachable from a(j)a^{(j)}.

Input

The first line contains an integer TT. Then TT test cases follow. In each test case, the first line contains two integers nn and mm. After that, mm lines follow. The kk-th of them contains nn integers a1(k),a2(k),…,an(k)a^{(k)}_1, a^{(k)}_2, \ldots, a^{(k)}_n. Each a(k)a^{(k)} is a permutation of 1,2,…,n1, 2, \ldots, n.

There are at most 10001000 small test cases and 11 large test case. The small test cases satisfy 1≤n≤51 \le n \le 5 and 1≤m≤5001 \le m \le 500. The large test case satisfies 1≤n≤91 \le n \le 9 and 1≤m≤3⋅1051 \le m \le 3 \cdot 10^5.

Output

For each test case, print the answer on a separate line.

Examples1

  1. Example 1

    Input
    2
    3 3
    1 2 3
    3 1 2
    2 3 1
    2 2
    1 2
    1 2
    
    Expected output
    5
    4