The Lost Cows

Time limit1sMemory limit128 MB

Summary
Given a synchronizing automaton over N states with M shared input letters, compute the maximum over all pairs of the shortest synchronizing word length for that pair.
Level

Hard8 of 10

Topics
BFS, Graph, Shortest path, Implementation
Solved
No attempts yet

Problem

On a sunny day, farmer John was kidnapped by the cows of his neighbor, farmer Marcus. The forced holiday does not bother him, but he wants to be sure that his own cows can end up together.

John's pastures are numbered 11 through NN, and one cow stands in each pasture. The barn is pasture 11. Every pasture has MM signs, and sign jj at pasture ii points along a path to pasture Si,jS_{i,j}. A sign sometimes points back to the pasture it stands in.

Marcus's cows let John write one list of instructions and hand it to all of his cows. An instruction is a single sign number. A cow reads the first number on the list, finds that sign in the pasture where she stands, and walks the path it points to. In the new pasture she reads the second number on the list and walks again the same way. She repeats this until the list runs out. Every cow follows the same list in the same order, so one instruction moves every cow one step.

John starts by working out how many instructions it takes to bring two cows into one pasture. For pastures aa and bb, let d(a,b)d(a, b) be the smallest length of a list such that the cow starting at aa and the cow starting at bb stand in the same pasture after the whole list has been followed. The two cows may be in different pastures along the way; only their positions after the last instruction have to match.

A list that gathers every cow at the barn is guaranteed to exist, so d(a,b)d(a, b) is defined for every pair aa, bb.

Input

The first line contains the number of pastures NN and the number of signs MM (3≤N≤2003 \le N \le 200, 1≤M≤2001 \le M \le 200).

Line jj of the next MM lines contains NN integers S1,j,S2,j,…,SN,jS_{1,j}, S_{2,j}, \dots, S_{N,j} (1≤Si,j≤N1 \le S_{i,j} \le N), where Si,jS_{i,j} is the pasture that sign jj at pasture ii points to.

Output

Print the largest value of d(a,b)d(a, b) over all pairs of pastures a<ba < b.

Examples3

  1. Example 1

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

    Input
    3 1
    1 1 1
    
    Expected output
    1
    
  3. Example 3

    Input
    5 1
    1 1 2 3 4
    
    Expected output
    4