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)

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*);
    }
}

#[allow(unused_imports)]
use std::cmp::{min, max};
#[allow(unused_imports)]
use std::io::{stdout, stdin, BufWriter, Write};

fn topological_sort(n: usize, edges: &Vec<Vec<usize>>) -> Vec<usize> {
    use std::collections::VecDeque;
    let mut st = VecDeque::new();

    let mut h = vec![0; n];
    for i in 0..n {
        for &e in edges[i].iter() {
            h[e] += 1;
        }
    }

    for i in 0..n {
        if h[i] == 0 {
            st.push_back(i);
        }
    }

    let mut ans = vec![];
    while let Some(i) = st.pop_front() {
        ans.push(i);
        for &t in edges[i].iter() {
            h[t] -= 1;
            if h[t] == 0 {
                st.push_back(t);
            }
        }
    }

    return ans
}

fn dfs(edges: &Vec<Vec<usize>>, cur: usize, t: usize, ans: &mut usize, d:usize) {
    if t == cur {
        *ans = max(d, *ans);
        return;
    }

    for &next in edges[cur].iter() {
        dfs(edges, next, t, ans, d+1);
    }
}

fn encode(a: usize, b:usize, n:usize) -> usize {
    let idx = n*a + b - (a+1) * (a+2) / 2;
    idx
}

fn main() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (write!(out,$($format)*).unwrap());
    }

    input!{
      n: usize,
      aa: [[usize1; n-1]; n],
    }
    // debug!(aa);

    use std::collections::HashMap;
    let mut edges = vec![vec![]; n*(n-1)/2];

    for i in 0..n {
        let mut a = i;
        for j in 0..n-2 {
            let mut a1 = a;
            let mut b1 = aa[i][j];
            if a1 > b1 {
                std::mem::swap(&mut a1, &mut b1);
            }

            let mut a2 = a;
            let mut b2 = aa[i][j+1];
            if a2 > b2 {
                std::mem::swap(&mut a2, &mut b2);
            }

            let mut i1 = encode(a1, b1, n);
            let mut i2 = encode(a2, b2, n);
            edges[i1].push(i2);
        }
    }

    for v in edges.iter_mut() {
        v.sort();
        v.dedup();
    }

    let order = topological_sort(n*(n-1)/2, &edges);
    if order.len() != n*(n-1)/2 {
        return puts!("{}\n", -1);
    }

    // for i in 0..n {
    let s = order[0];
    let t = order[order.len()-1];
    let mut ans = 0;
    dfs(&edges, s, t, &mut ans, 0);
    puts!("{}\n", ans+1);
}