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.42.0) (judge verdict: Wrong Answer)

#[allow(unused_imports)]
use itertools::Itertools;
#[allow(unused_imports)]
use num::*;
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::collections::*;

pub struct WeightedGraph {
    graph: Vec<Vec<(usize, i64)>>,
    v: usize,
}

type WeightedEdge = (usize, usize, i64);
impl WeightedGraph {
    const INF: i64 = 1 << 60;

    pub fn new(edges: &[WeightedEdge], v: usize) -> Self {
        let mut graph = vec![Vec::new(); v];
        for &(u, v, w) in edges {
            graph[u].push((v, w));
            graph[v].push((u, w));
        }
        Self { graph, v }
    }

    pub fn new_directed(edges: &[WeightedEdge], v: usize) -> Self {
        let mut graph = vec![Vec::new(); v];
        for &(u, v, w) in edges {
            graph[u].push((v, w));
        }
        Self { graph, v }
    }

    pub fn bellman_ford(&self, s: usize) -> Option<Vec<Option<i64>>> {
        let v = self.v;
        let inf = Self::INF;
        let mut cost_list = vec![inf; v];
        cost_list[s] = 0;
        let mut count = 0;
        loop {
            let mut updated = false;
            for u in 0..v {
                for &(v, w) in &self.graph[u] {
                    if cost_list[u] != inf && cost_list[u] + w < cost_list[v] {
                        cost_list[v] = cost_list[u] + w;
                        updated = true;
                    }
                }
            }
            if !updated {
                return Some(self.optionalize(cost_list));
            }
            count += 1;
            if count == v {
                return None;
            }
        }
    }

    pub fn solve(&self, que: VecDeque<usize>, indegreev: &mut Vec<usize>) -> usize {
        let mut res = 1;
        let mut que = self.next_que(que, indegreev);
        loop {
            if que.len() == 0 {
                break;
            }
            res += 1;
            que = self.next_que(que, indegreev);
        }
        res
    }

    fn next_que(&self, mut que: VecDeque<usize>, indegreev: &mut Vec<usize>) -> VecDeque<usize> {
        let mut res = VecDeque::new();
        while let Some(u) = que.pop_front() {
            for &(v, _) in &self.graph[u] {
                indegreev[v] -= 1;
                if indegreev[v] == 0 {
                    res.push_back(v);
                }
            }
        }
        res
    }

    fn optionalize(&self, v: Vec<i64>) -> Vec<Option<i64>> {
        v.into_iter()
            .map(|x| if x == Self::INF { None } else { Some(x) })
            .collect::<Vec<_>>()
    }
}

fn solve() {
    input! {
        n: usize,
        matchv: [[Usize1; n - 1]; n]
    };

    let vn = n * (n - 1) / 2;
    let mut indegreev = vec![0; vn];
    let mut edges = Vec::new();
    let mut id_table: HashMap<(usize, usize), usize> = HashMap::new();
    let mut cur_id = 0;
    for i in 0..n {
        let a = i;
        for mv in matchv[i].windows(2) {
            let b = mv[0];
            let key = (a.min(b), a.max(b));
            let u = match id_table.get(&key) {
                Some(id) => *id,
                None => {
                    let id = cur_id;
                    id_table.insert(key, id);
                    cur_id += 1;
                    id
                }
            };
            let c = mv[1];
            let key = (a.min(c), a.max(c));
            let v = match id_table.get(&key) {
                Some(id) => *id,
                None => {
                    let id = cur_id;
                    id_table.insert(key, id);
                    cur_id += 1;
                    id
                }
            };
            indegreev[v] += 1;
            edges.push((u, v, 1));
        }
    }

    let graph = WeightedGraph::new_directed(&edges, vn);
    let mut que = VecDeque::new();
    for u in 0..vn {
        if indegreev[u] == 0 {
            que.push_back(u);
        }
    }
    if que.is_empty() {
        println!("-1");
        return;
    }
    for &s in &que {
        if graph.bellman_ford(s).is_none() {
            println!("-1");
            return;
        }
    }
    let res = graph.solve(que, &mut indegreev);
    println!("{}", res);
}

fn main() {
    std::thread::Builder::new()
        .name("big stack size".into())
        .stack_size(256 * 1024 * 1024)
        .spawn(|| {
            solve();
        })
        .unwrap()
        .join()
        .unwrap();
}