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: Accepted)

#![allow(unused_imports, unused_macros, dead_code)]

macro_rules! min {
    (.. $x:expr) => {{
        let mut it = $x.iter();
        if let Some(z) = it.next() {
            Some(it.fold(z, |x, y| min!(x, y)))
        } else {
            None
        }
    }};
    ($x:expr) => ($x);
    ($x:expr, $($ys:expr),*) => {{
        let t = min!($($ys),*);
        if $x < t { $x } else { t }
    }}
}
macro_rules! max {
    (.. $x:expr) => {{
        let mut it = $x.iter();
        if let Some(z) = it.next() {
            Some(it.fold(z, |x, y| max!(x, y)))
        } else {
            None
        }
    }};
    ($x:expr) => ($x);
    ($x:expr, $($ys:expr),*) => {{
        let t = max!($($ys),*);
        if $x > t { $x } else { t }
    }}
}


macro_rules! ewriteln {
    ($($args:expr),*) => { let _ = writeln!(&mut std::io::stderr(), $($args),*); };
}
macro_rules! trace {
    ($x:expr) => { ewriteln!(">>> {} = {:?}", stringify!($x), $x) };
    ($($xs:expr),*) => { trace!(($($xs),*)) }
}
macro_rules! put {
    (.. $x:expr) => {{
        let mut it = $x.iter();
        if let Some(x) = it.next() { print!("{}", x); }
        for x in it { print!(" {}", x); }
        println!("");
    }};
    ($x:expr) => { println!("{}", $x) };
    ($x:expr, $($xs:expr),*) => { print!("{} ", $x); put!($($xs),*) }
}

const M: i64 = 1_000_000_007;

fn main() {

    let mut sc = Scanner::new();
    let n: usize = sc.cin();
    let t: usize = n * (n - 1) / 2;

    use std::collections::HashMap;
    let mut task_id = HashMap::new();
    {
        let mut k = 0usize;
        for i in 0..n {
            for j in 0..i {
                task_id.insert((i, j), k);
                task_id.insert((j, i), k);
                k += 1;
            }
        }
    }

    let mut rev = vec![vec![]; t];
    {
        for i in 0..n {
            let js: Vec<_> = (1..n).map(|_| sc.cin::<usize>()).map(|k| k - 1).collect();
            for k in 0..n-2 {
                let u = *task_id.get(&(i, js[k])).unwrap();
                let v = *task_id.get(&(i, js[k+1])).unwrap();
                rev[v].push(u);
            }
        }
    }
    // trace!(&rev);

    let mut dp: Vec<Option<u64>> = vec![None; t];
    {
        for u in 0..t {
            if rev[u].len() == 0 {
                dp[u] = Some(1);
            }
        }
        for u in 0..t {
            if dp[u].is_some() { continue }
            let mut reserved = vec![false; t];
            let mut stack = vec![(false, u), (true, u)];
            while let Some((dir, u)) = stack.pop() {
                if dp[u].is_some() { continue }
                if dir {
                    if reserved[u] {
                        put!(-1);
                        return;
                    }
                    reserved[u] = true;
                    for &v in rev[u].iter() {
                        if dp[v].is_some() { continue }
                        stack.push((false, v));
                        stack.push((true, v));
                    }
                } else {
                    if dp[u].is_some() { continue }
                    if let Some(mx) = rev[u].iter().map(|&v| dp[v].unwrap()).max() {
                        dp[u] = Some(1 + mx);
                    } else {
                        dp[u] = Some(1);
                    }
                }
            }
        }
    }
    // trace!(&dp);
    put!(dp.iter().max().unwrap().unwrap());
}

use std::io::{self, Write};
use std::str::FromStr;
use std::collections::VecDeque;

struct Scanner { stdin: io::Stdin, buffer: VecDeque<String>, }
impl Scanner {
    fn new() -> Self { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }
    fn cin<T: FromStr>(&mut self) -> T {
        while self.buffer.len() == 0 {
            let mut line = String::new();
            let _ = self.stdin.read_line(&mut line);
            for w in line.split_whitespace() {
                self.buffer.push_back(String::from(w));
            }
        }
        self.buffer.pop_front().unwrap().parse::<T>().ok().unwrap()
    }
}