Problem:
Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

1 \leq A_{i, j} \leq N

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

4
2 3 4
1 3 4
4 1 2
3 1 2

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.

Solution in Rust (1.15.1) (judge verdict: Time Limit Exceeded)

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

type Game = (usize, usize, usize); // p1, p2, id
type IdandTrace = (usize, bool); // id, forFinished

fn main() {
    let n = read::<usize>();
    let m = n * (n - 1); // Num of Games

    let mut initial_games: Vec<Game> = Vec::with_capacity(n);
    let mut graph: Vec<Vec<Game>> = vec![Vec::with_capacity(m); m];
    let mut input: Vec<i32> = vec![0;m];
    for i in 0..n {
        let row = read_vec::<usize>();
        if row.len() <= 0 {
            continue;
        }
        let mut g_prev = get_game(n, i, row[0]);
        initial_games.push(g_prev);
        for j in 1..row.len() {
            let g = get_game(n, i, row[j]);
            graph[g_prev.2].push(g);
            input[g.2] += 1;
            g_prev = g;
        }
    }

    //println!("IIIIIII {:?}", input);

    let d = solve(n, m, &graph, &initial_games, &input);
    println!("{}", d);
}

fn get_game(n: usize, i: usize, j: usize) -> Game {
    let mut p1 = i;
    let mut p2 = j - 1;
    if p1 > p2 {
        let tmp = p1;
        p1 = p2;
        p2 = tmp;
    }
    return (p1, p2, p1 * n + p2);
}

fn solve(n: usize, m: usize, graph: &[Vec<Game>], initial_games: &[Game], input: &[i32]) -> i32 {
    //println!("XXX 000 {}, {}", n, m);
    let mut lp:Vec<(bool, i32)> = vec![(false, 0); m];
    let mut max: i32 = -1;
    for g in initial_games {
        //println!("XXXXXX g = {:?}", g);
        if input[g.2] > 0 {
            //println!("XXXXXXXX input > 0!");
            // このcontinueを有効にするとWAになる。
            // 全員 input > 0 のときに注意！
            continue;
        }
        
        if lp[g.2].0 {
            // Already tried.
            continue;
        }
        let d = dfs(n, m, graph, g, &lp);
        //println!("XXXXXX d = {} --> {}", d, g.2);
        lp[g.2] = (true, d);
        if d < 0 {
            return d;
        }
        if d > max {
            max = d;
        }
    }
    // Num of nodes = distance + 1
    if max >= 0 {
        max += 1;
    }
    return max;
}

/**
 * Calculate the length of the longest path by DFS.
 * Returns -1 if it contains the cycle.
 */
fn dfs(n: usize, m: usize, graph: &[Vec<Game>], initial_game: &Game, lp: &[(bool, i32)]) -> i32 {
    let mut visited: Vec<bool> = vec![false; m];
    let mut finished: Vec<bool> = vec![false; m];

    let mut d: Vec<i32> = vec![0; m];
    let mut stack: Vec<IdandTrace> = Vec::with_capacity(m);

    stack.push((initial_game.2, false));
    let mut max = 0;
    while !stack.is_empty() {
        let iat = stack.pop().unwrap();
        

        // A. Fin entry
        if iat.1 {
            finished[iat.0] = true;
            continue;
        }

        //println!("\nYYYY iat = {}, d={}", iat.0, d[iat.0]);

        // B. Normal entry
        visited[iat.0] = true;
        stack.push((iat.0, true));

        // B-1 No child
        if graph[iat.0].len() == 0 {
            continue;
        }

        // B-3 Some children
        let new_d = d[iat.0] + 1;
        for next in &graph[iat.0] {
            //println!("YYY {:?}", next);
            if visited[next.2] && !finished[next.2] {
                // Cycle!
                //println!("YYY Cycle!");
                return -1;
            }

            if lp[next.2 % n].0 {
                //println!("YYY Already tried: {:?}", lp[next.2]);
                // Already tried.
                if lp[next.2].1 < 0 {
                    return -1;
                }
                //return new_d + lp[next.2].1;
            }


            if d[next.2] < new_d {
                //println!("YYY Update to {}", new_d);
                // Update
                d[next.2] = new_d;
                stack.push((next.2, false));
                if new_d > max {
                    max = new_d;
                }
            }
        }
    }
    return max;
}