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: Wrong Answer)

#![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();

    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![]; task_id.len()];
    {
        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 visited = vec![false; task_id.len()];
    let mut ord = vec![];
    let mut ind = vec![0; task_id.len()];
    for u in 0..task_id.len() {
        if visited[u] { continue }
        let mut stack = vec![(false, u), (true, u)];
        while let Some((dir, u)) = stack.pop() {
            if dir {
                visited[u] = true;
                for &v in rev[u].iter() {
                    if visited[v] { continue }
                    stack.push((false, v));
                    stack.push((true, v));
                }
            } else {
                ind[u] = ord.len();
                ord.push(u);
            }
        }
    }
    trace!(&ord);
    trace!(&ind);

    // cycle?
    let mut ok = true;
    for u in 0..task_id.len() {
        for &v in rev[u].iter() {
            if ind[u] < ind[v] {
                ok = false;
                break;
            }
        }
    }
    if !ok {
        put!(-1);
        return;
    }

    let mut dp = vec![0; task_id.len()];
    for u in 0..task_id.len() {
        dp[u] = rev[u].iter().map(|&v| dp[v]).fold(1, |a, x| max!(a, 1 + x));
    }
    trace!(&dp);

    put!(dp.iter().max().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()
    }
}