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 C# (Mono 4.6.2.0) (judge verdict: Wrong Answer)

#if DEBUG
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif

using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace Contest
{
    class Program
    {
        static void Main(string[] args)
        {
            var scanner = new IO.StreamScanner(Console.OpenStandardInput());
            var n = scanner.Integer();

            var graphs = new List<List<int>>();
            for (int i = 0; i < n; i++)
                graphs.Add(scanner.ScanLine().Split().Select(v => int.Parse(v) - 1).ToList());
            var ans = GetAns(n, graphs);
            IO.Printer.Out.WriteLine(ans);
            IO.Printer.Out.Flush();
        }
        
        public class Node
        {
            public int ID;
            public int P1;
            public int P2;
            public List<Node> Nexts = new List<Node>();
            public List<Node> Prevs = new List<Node>();

            // p1 < p2
            public Node(int p1, int p2)
            {
                P1 = p1;
                P2 = p2;
                ID = p1 << 16 | p2;
            }
        }

        public class QueNode : IComparable
        {
            public int Dist;
            public Node Node;

            public QueNode(int dist, Node node)
            {
                Dist = dist;
                Node = node;
            }

            public int CompareTo(object obj)
            {
                var oth = obj as QueNode;
                return Dist.CompareTo(oth.Dist);
            }
        }

        public static Dictionary<int, Node> GetAllNodes(int n)
        {
            var ret = new Dictionary<int, Node>();
            for(int i=0; i<n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    var node = new Node(i, j);
                    ret.Add(i << 16 | j, node);
                }
            }
            return ret;
        }

        public static long GetAns(int n, List<List<int>> map)
        {
            var allNodes = GetAllNodes(n);

            for (int i = 0; i < n; i++)
            {
                Node prev = null;
                foreach(var match in map[i])
                {
                    var node = allNodes[GetId(i, match)];
                    if (prev != null)
                    {
                        prev.Nexts.Add(node);
                        node.Prevs.Add(prev);
                    }
                    prev = node;
                }
            }

            var startNodes = allNodes.Values.Where(x => !x.Prevs.Any()).ToList();
            var endNodes = allNodes.Values.Where(x => !x.Nexts.Any()).ToList();

            var durations = startNodes
                .Select(v => GetDuration(n, v, endNodes)).ToList();

            if (!durations.Any() || durations.Any(d => d == -1)) return -1;
            return durations.Max();
        }

        public static long GetDuration(int n, Node s, List<Node> endNodes)
        {
            var ret = 0L;
            var que = new PriorityQueue<QueNode>(1);
            que.Push(new QueNode(1, s));

            var dists = new Dictionary<Node, int>();
            while (que.Count() > 0)
            {
                var cur = que.Pop();
                if (dists.ContainsKey(cur.Node) && dists[cur.Node] >= cur.Dist) continue;
                dists[cur.Node] = cur.Dist;

                if (cur.Dist > n * 2) return -1;
                foreach (var next in cur.Node.Nexts)
                {
                    que.Push(new QueNode(cur.Dist + 1, next));
                }
            }

            foreach(var e in endNodes)
            {
                if (!dists.ContainsKey(e)) continue;
                ret = Math.Max(ret, dists[e]);
            }

            return ret;
        }

        public static int GetId(int i, int j)
        {
            if (i < j) return i << 16 | j;
            return j << 16 | i;
        }
    }

    public class PriorityQueue<T> where T : IComparable
    {
        private IComparer<T> _comparer = null;
        private int _type = 0;

        private T[] _heap;
        private int _sz = 0;

        private int _count = 0;

        /// <summary>
        /// Priority Queue with custom comparer
        /// </summary>
        public PriorityQueue(IComparer<T> comparer)
        {
            _heap = new T[128];
            _comparer = comparer;
        }

        /// <summary>
        /// Priority queue
        /// </summary>
        /// <param name="type">0: asc, 1:desc</param>
        public PriorityQueue(int type = 0)
        {
            _heap = new T[128];
            _type = type;
        }

        private int Compare(T x, T y)
        {
            if (_comparer != null) return _comparer.Compare(x, y);
            return _type == 0 ? x.CompareTo(y) : y.CompareTo(x);
        }

        public void Push(T x)
        {
            _count++;
            if (_count > _heap.Length)
            {
                var newheap = new T[_heap.Length * 2];
                for (int n = 0; n < _heap.Length; n++) newheap[n] = _heap[n];
                _heap = newheap;
            }

            //node number
            var i = _sz++;

            while (i > 0)
            {
                //parent node number
                var p = (i - 1) / 2;

                if (Compare(_heap[p], x) <= 0) break;

                _heap[i] = _heap[p];
                i = p;
            }

            _heap[i] = x;
        }

        public T Pop()
        {
            _count--;

            T ret = _heap[0];
            T x = _heap[--_sz];

            int i = 0;
            while (i * 2 + 1 < _sz)
            {
                //children
                int a = i * 2 + 1;
                int b = i * 2 + 2;

                if (b < _sz && Compare(_heap[b], _heap[a]) < 0) a = b;

                if (Compare(_heap[a], x) >= 0) break;

                _heap[i] = _heap[a];
                i = a;
            }

            _heap[i] = x;

            return ret;
        }

        public int Count()
        {
            return _count;
        }

        public T Peek()
        {
            return _heap[0];
        }

        public bool Contains(T x)
        {
            for (int i = 0; i < _sz; i++) if (x.Equals(_heap[i])) return true;
            return false;
        }

        public void Clear()
        {
            while (this.Count() > 0) this.Pop();
        }

        public IEnumerator<T> GetEnumerator()
        {
            var ret = new List<T>();

            while (this.Count() > 0)
            {
                ret.Add(this.Pop());
            }

            foreach (var r in ret)
            {
                this.Push(r);
                yield return r;
            }
        }

        public T[] ToArray()
        {
            T[] array = new T[_sz];
            int i = 0;

            foreach (var r in this)
            {
                array[i++] = r;
            }

            return array;
        }
    }


#if DEBUG

    [TestClass]
    public class Test
    {
        [TestMethod]
        public void Test1()
        {
            var n = 3;
            var map = new List<List<int>>
            {
                new List<int>{ 1, 2},
                new List<int>{0, 2},
                new List<int>{0, 1},
            };
            var exp = 3;
            var ans = Program.GetAns(n, map);
            Assert.AreEqual(exp, ans);
        }

        [TestMethod]
        public void Test2()
        {
            var n = 4;
            var map = new List<List<int>>
            {
                new List<int>{ 1, 2, 3 },
                new List<int>{ 0, 2, 3 },
                new List<int>{ 3, 0, 1 },
                new List<int>{ 2, 0, 1 },
            };
            var exp = 4;
            var ans = Program.GetAns(n, map);
            Assert.AreEqual(exp, ans);
        }

        [TestMethod]
        public void Test3()
        {
            var n = 3;
            var map = new List<List<int>>
            {
                new List<int>{ 1, 2  },
                new List<int>{ 2, 0 },
                new List<int>{0, 1},
            };
            var exp = -1;
            var ans = Program.GetAns(n, map);
            Assert.AreEqual(exp, ans);
        }

        public bool IsEq<T>(List<T> l1, List<T> l2)
        {
            if (l1.Count() != l2.Count()) return false;
            for (int i = 0; i < l1.Count(); i++)
            {
                if (!l1[i].Equals(l2[i])) return false;
            }
            return true;
        }

    }
#endif
}

namespace IO
{
    using System.IO;
    using System.Text;
    using System.Globalization;

    public class Printer : StreamWriter
    {
        static Printer()
        {
            Out = new Printer(Console.OpenStandardOutput()) { AutoFlush = false };
        }

        public static Printer Out { get; set; }

        public override IFormatProvider FormatProvider
        {
            get { return CultureInfo.InvariantCulture; }
        }

        public Printer(Stream stream)
            : base(stream, new UTF8Encoding(false, true))
        {
        }

        public Printer(Stream stream, Encoding encoding)
            : base(stream, encoding)
        {
        }

        public void Write<T>(string format, T[] source)
        {
            base.Write(format, source.OfType<object>().ToArray());
        }

        public void WriteLine<T>(string format, T[] source)
        {
            base.WriteLine(format, source.OfType<object>().ToArray());
        }
    }

    public class StreamScanner
    {
        public StreamScanner(Stream stream)
        {
            str = stream;
        }

        public readonly Stream str;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        public bool isEof;

        public bool IsEndOfStream
        {
            get { return isEof; }
        }

        private byte read()
        {
            if (isEof) return 0;
            if (ptr < len) return buf[ptr++];
            ptr = 0;
            if ((len = str.Read(buf, 0, 1024)) > 0) return buf[ptr++];
            isEof = true;
            return 0;
        }

        public char Char()
        {
            byte b;
            do b = read(); while ((b < 33 || 126 < b) && !isEof);
            return (char)b;
        }

        public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }

        public string ScanLine()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b != '\n'; b = (char)read())
                if (b == 0) break;
                else if (b != '\r') sb.Append(b);
            return sb.ToString();
        }

        public long Long()
        {
            if (isEof) return long.MinValue;
            long ret = 0;
            byte b;
            var ng = false;
            do b = read(); while (b != 0 && b != '-' && (b < '0' || '9' < b));
            if (b == 0) return long.MinValue;
            if (b == '-')
            {
                ng = true;
                b = read();
            }
            for (; ; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                ret = ret * 10 + b - '0';
            }
        }

        public int Integer()
        {
            return (isEof) ? int.MinValue : (int)Long();
        }

        public double Double()
        {
            var s = Scan();
            return s != "" ? double.Parse(s, CultureInfo.InvariantCulture) : double.NaN;
        }

        static T[] enumerate<T>(int n, Func<T> f)
        {
            var a = new T[n];
            for (int i = 0; i < n; ++i) a[i] = f();
            return a;
        }

        public char[] Char(int n)
        {
            return enumerate(n, Char);
        }

        public string[] Scan(int n)
        {
            return enumerate(n, Scan);
        }

        public double[] Double(int n)
        {
            return enumerate(n, Double);
        }

        public int[] Integer(int n)
        {
            return enumerate(n, Integer);
        }

        public long[] Long(int n)
        {
            return enumerate(n, Long);
        }
    }
}