CF BUDDY
← Problems·

1792D · Fixed Prefix Permutations

1700 · binary search, bitmasks, data structures

Problem: You are given nn permutations a1,a2,,ana_1, a_2, \dots, a_n, each of length mm. Recall that a permutation of length mm is a sequence of mm distinct integers from 11 to mm.

Let the beauty of a permutation p1,p2,,pmp_1, p_2, \dots, p_m be the largest kk such that p1=1,p2=2,,pk=kp_1 = 1, p_2 = 2, \dots, p_k = k. If p11p_1 \neq 1, then the beauty is 00.

The product of two permutations pqp \cdot q is a permutation rr such that rj=qpjr_j = q_{p_j}.

For each ii from 11 to nn, print the largest beauty of a permutation aiaja_i \cdot a_j over all jj from 11 to nn (possibly, i=ji = j).

Input Format: The first line contains a single integer tt (1t1041 \le t \le 10^4) — the number of testcases.

The first line of each testcase contains two integers nn and mm (1n51041 \le n \le 5 \cdot 10^4; 1m101 \le m \le 10) — the number of permutations and the length of each permutation.

The ii-th of the next nn lines contains a permutation aia_i — mm distinct integers from 11 to mm.

The sum of nn doesn't exceed 51045 \cdot 10^4 over all testcases.

Output Format: For each testcase, print nn integers. The ii-th value should be equal to the largest beauty of a permutation aiaja_i \cdot a_j over all jj (1jn1 \le j \le n).

Sample Cases

Case 1

Input

3
3 4
2 4 1 3
1 2 4 3
2 1 3 4
2 2
1 2
2 1
8 10
3 4 9 6 10 2 7 8 1 5
3 9 1 8 5 7 4 10 2 6
3 10 1 7 5 9 6 4 2 8
1 2 3 4 8 6 10 7 9 5
1 2 3 4 10 6 8 5 7 9
9 6 1 2 10 4 7 8 3 5
7 9 3 2 5 6 4 8 1 10
9 4 3 7 5 6 1 10 8 2

Output

1 4 4 
2 2 
10 8 1 6 8 10 1 7

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback