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];
    for i in 0..n {
        let row = read_vec::<usize>();
        if row.len() <= 1 {
            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);
            g_prev = g;
        }
    }

    let d = solve(m, &graph, &initial_games);
    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(m: usize, graph: &[Vec<Game>], initial_games: &[Game]) -> i32 {
    let mut max: i32 = -1;
    for g in initial_games {
        let d = dfs(m, graph, g);
        if d < 0 {
            return d;
        }
        if d > max {
            max = d;
        }
    }
    // Num of nodes = distance + 1
    return max + 1;
}

/**
 * Calculate the length of the longest path by DFS.
 * Returns -1 if it contains the cycle.
 */
fn dfs(m: usize, graph: &[Vec<Game>], initial_game: &Game) -> 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;
        }

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

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

        // B-2 Some children
        let new_d = d[iat.0] + 1;
        for next in &graph[iat.0] {
            if visited[next.2] && !finished[next.2] {
                // Cycle!
                return -1;
            }
            if d[next.2] < new_d {
                // Update
                d[next.2] = new_d;
                stack.push((next.2, false));
                if new_d > max {
                    max = new_d;
                }
            }
        }
    }
    return max;
}