Las matrices son divertidas#13036

Las matrices son divertidas (Editorial)

Problem Author:

Hasan Saleh (MathModel)

Prepared by:

Hasan Saleh (MathModel)

Edited by:

Hasan Saleh (MathModel)

Solution Shifts never mix columns, so each column is independent. Column must end up as j+1,\,j+1+m,\,\dots,\,j+1+(n-1)m, and a cyclic shift only preserves the cyclic order, so it is Perfect iff it is a rotation of that progression. Rotating the minimum to the top canonicalizes it, thus checking that all consecutive differences equal and that (col_0-1)\bmod m=j is enough and sufficient. Complexity O(n\cdot m).

def solve():
    n,m=map(int,input().split())
    a=[list(map(int,input().split())) for _ in range(n)]
    ans=0
    for j in range(m):
        col=[a[i][j] for i in range(n)]
        p=min(range(n),key=col.__getitem__)
        col=col[p:]+col[:p]
        ok=((col[0]-1)%m==j and all(col[i+1]-col[i]==m for i in range(n-1)))
        if(ok):
            ans+=1
    print(ans)
        
for _ in range(int(input())):
    solve()