Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 1 << 60


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    g = defaultdict(list)
    rg = defaultdict(set)

    V = set()

    def ij2v(i, j):
        if i > j:
            i, j = j, i
        return i * 10**6 + j
    for i, a in enumerate(A, start=1):
        for j in range(len(a)-1):
            u = ij2v(i, a[j])
            v = ij2v(i, a[j+1])
            g[u].append(v)
            rg[v].add(u)
            V.add(u)
            V.add(v)

    s = []
    for v in V:
        if not rg[v]:
            s.append(v)

    done = len(s)
    ans = 0
    while s:
        ans += 1
        ns = []
        for u in s:
            for v in g[u]:
                # if v in done:
                #     continue
                rg[v].remove(u)
                if len(rg[v]) == 0:
                    ns.append(v)
                    done += 1
        s = ns

    if done != N * (N-1) // 2:
        return -1

    return ans



def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 1 << 60


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    g = defaultdict(list)
    rg = defaultdict(set)

    V = set()

    def ij2v(i, j):
        if i > j:
            i, j = j, i
        return i * 10**6 + j
    for i, a in enumerate(A, start=1):
        for j in range(len(a)-1):
            u = ij2v(i, a[j])
            v = ij2v(i, a[j+1])
            g[u].append(v)
            rg[v].add(u)
            V.add(u)
            V.add(v)

    s = []
    for v in V:
        if not rg[v]:
            s.append(v)

    done = set(s)
    ans = 0
    while s:
        ans += 1
        ns = []
        for u in s:
            for v in g[u]:
                if v in done:
                    continue
                rg[v].remove(u)
                if len(rg[v]) == 0:
                    ns.append(v)
                    done.add(v)
        s = ns

    if len(done) != N * (N-1) // 2:
        return -1

    return ans



def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 1 << 60


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    g = defaultdict(list)
    rg = defaultdict(set)

    V = set()

    def ij2v(i, j):
        if i > j:
            i, j = j, i
        return i * 10**6 + j
    for i, a in enumerate(A, start=1):
        for j in range(len(a)-1):
            u = ij2v(i, a[j])
            v = ij2v(i, a[j+1])
            g[u].append(v)
            rg[v].add(u)
            V.add(u)
            V.add(v)

    s = []
    for v in V:
        if rg[v]:
            pass
        else:
            s.append(v)

    done = set(s)
    ans = 0
    while s:
        ans += 1
        ns = []
        for u in s:
            for v in g[u]:
                if v in done:
                    continue
                rg[v].remove(u)
                if len(rg[v]) == 0:
                    ns.append(v)
                    done.add(v)
        s = ns

    if len(done) != N * (N-1) // 2:
        return -1

    return ans



def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 1 << 60


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    g = defaultdict(list)
    rg = defaultdict(set)

    V = set()
    for i, a in enumerate(A, start=1):
        for j in range(len(a)-1):
            u = (min(i, a[j]), max(i, a[j]))
            v = (min(i, a[j+1]), max(i, a[j+1]))
            g[u].append(v)
            rg[v].add(u)
            V.add(u)
            V.add(v)

    s = []
    for v in V:
        if rg[v]:
            pass
        else:
            s.append(v)

    done = set(s)
    ans = 0
    while s:
        ans += 1
        ns = []
        for u in s:
            for v in g[u]:
                if v in done:
                    continue
                rg[v].remove(u)
                if len(rg[v]) == 0:
                    ns.append(v)
                    done.add(v)
        s = ns

    if len(done) != N * (N-1) // 2:
        return -1

    return ans



def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()

    def update(i):
        if not A[i-1]:
            return

        d = A[i-1][-1]
        n = (min(i, d), max(i, d))
        if n not in s1:
            s1.add(n)
        else:
            s2.add(n)
            s1.remove(n)

    for i in range(1, N+1):
        update(i)

    while s2:
        ans += 1
        s2_, s2 = s2, set()
        for k in s2_:
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            update(a)
            update(b)


    for a in A:
        if a:
            return -1
    return ans


def TSort(g):
    V = set(g.keys())
    for v in g.values():
        V |= set(v)
    V = tuple(V)
    funin = Counter()

    for u in V:
        for v in g[u]:
            funin[v] += 1

    q = deque()
    for v in V:
        if funin[v] == 0:
            q.append(v)
    L = []
    while q:
        u = q.popleft()
        L.append(u)
        for v in g[u]:
            funin[v] -= 1
            if funin[v] == 0:
                q.append(v)
    return L

@mt
def slv2(N, A):
    g = defaultdict(list)
    
    for i, a in enumerate(A):
        i += 1
        for j in range(1, N-1):
            u = (min(i, a[j-1]), max(i, a[j-1]))
            v = (min(i, a[j]), max(i, a[j]))
            g[u].append(v)
    sv = TSort(g)
    if len(sv) != N*(N-1)//2:
        return -1
    
    dp = defaultdict(lambda:0)
    for u in sv:
        for v in g[u]:
            dp[v] = max(dp[v], dp[u]+1)
    return dp[sv[-1]] + 1


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv2(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()

    def update(i):
        if not A[i-1]:
            return

        d = A[i-1][-1]
        n = (min(i, d), max(i, d))
        if n not in s1:
            s1.add(n)
        else:
            s2.add(n)
            s1.remove(n)

    for i in range(1, N+1):
        update(i)

    while s2:
        ans += 1
        s2_, s2 = s2, set()
        for k in s2_:
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            update(a)
            update(b)


    for a in A:
        if a:
            return -1
    return ans


def TSort(g):
    V = set(g.keys())
    for v in g.values():
        V |= set(v)
    V = tuple(V)
    funin = Counter()

    for u in V:
        for v in g[u]:
            funin[v] += 1

    q = deque()
    for v in V:
        if funin[v] == 0:
            q.append(v)
    L = []
    while q:
        u = q.popleft()
        L.append(u)
        for v in g[u]:
            funin[v] -= 1
            if funin[v] == 0:
                q.append(v)
    return L

@mt
def slv2(N, A):
    g = defaultdict(list)
    
    for i, a in enumerate(A):
        i += 1
        for j in range(1, N-1):
            u = (min(i, a[j-1]), max(i, a[j-1]))
            v = (min(i, a[j]), max(i, a[j]))
            g[u].append(v)
    sv = TSort(g)
    if len(sv) != N*(N-1)//2:
        return -1
    
    dp = defaultdict(lambda:0)
    for u in sv:
        for v in g[u]:
            dp[v] = max(dp[v], dp[u]+1)
    return dp[sv[-1]] + 1


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv2(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()

    def update(i):
        if not A[i-1]:
            return

        d = A[i-1][-1]
        n = (min(i, d), max(i, d))
        if n not in s1:
            s1.add(n)
        else:
            s2.add(n)
            s1.remove(n)

    for i in range(1, N+1):
        update(i)

    while s2:
        ans += 1
        s2_, s2 = s2, set()
        for k in s2_:
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            update(a)
            update(b)


    for a in A:
        if a:
            return -1
    return ans


def TSort(g):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = tuple(set(V))
    funin = Counter()

    for u in V:
        for v in g[u]:
            funin[v] += 1

    q = deque()
    for v in V:
        if funin[v] == 0:
            q.append(v)
    L = []
    while q:
        u = q.popleft()
        L.append(u)
        for v in g[u]:
            funin[v] -= 1
            if funin[v] == 0:
                q.append(v)
    return L

@mt
def slv2(N, A):
    g = defaultdict(list)
    
    for i, a in enumerate(A):
        i += 1
        for j in range(1, N-1):
            u = (min(i, a[j-1]), max(i, a[j-1]))
            v = (min(i, a[j]), max(i, a[j]))
            g[u].append(v)
    sv = TSort(g)
    if len(sv) != N*(N-1)//2:
        return -1
    
    dp = defaultdict(lambda:0)
    for u in sv:
        for v in g[u]:
            dp[v] = max(dp[v], dp[u]+1)
    return dp[sv[-1]] + 1


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv2(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()

    def update(i):
        if not A[i-1]:
            return

        d = A[i-1][-1]
        n = (min(i, d), max(i, d))
        if n not in s1:
            s1.add(n)
        else:
            s2.add(n)
            s1.remove(n)

    for i in range(1, N+1):
        update(i)

    while s2:
        ans += 1
        s2_, s2 = s2, set()
        for k in s2_:
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            update(a)
            update(b)


    for a in A:
        if a:
            return -1
    return ans


def TSort(g):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = set(V)
    funin = Counter()

    for u in V:
        for v in g[u]:
            funin[v] += 1

    q = deque()
    for v in V:
        if funin[v] == 0:
            q.append(v)
    L = []
    while q:
        u = q.popleft()
        L.append(u)
        for v in g[u]:
            funin[v] -= 1
            if funin[v] == 0:
                q.append(v)
    return L

@mt
def slv2(N, A):
    g = defaultdict(list)
    
    for i, a in enumerate(A):
        i += 1
        for j in range(1, N-1):
            u = (min(i, a[j-1]), max(i, a[j-1]))
            v = (min(i, a[j]), max(i, a[j]))
            g[u].append(v)
    sv = TSort(g)
    if len(sv) != N*(N-1)//2:
        return -1
    
    dp = defaultdict(lambda:0)
    for u in sv:
        for v in g[u]:
            dp[v] = max(dp[v], dp[u]+1)
    return dp[sv[-1]] + 1


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv2(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()

    def update(i):
        if not A[i-1]:
            return

        d = A[i-1][-1]
        n = (min(i, d), max(i, d))
        if n not in s1:
            s1.add(n)
        else:
            s2.add(n)
            s1.remove(n)

    for i in range(1, N+1):
        update(i)

    while s2:
        ans += 1
        s2_, s2 = s2, set()
        for k in s2_:
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            update(a)
            update(b)


    for a in A:
        if a:
            return -1
    return ans


def TSort(g):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = set(V)
    funin = Counter()

    for u in V:
        for v in g[u]:
            funin[v] += 1

    q = deque()
    for v in V:
        if funin[v] == 0:
            q.append(v)
    L = []
    while q:
        u = q.popleft()
        L.append(u)
        for v in g[u]:
            funin[v] -= 1
            if funin[v] == 0:
                q.append(v)
    return L

@mt
def slv2(N, A):
    g = defaultdict(list)
    
    for i, a in enumerate(A):
        i += 1
        for j in range(1, N-1):
            u = (min(i, a[j-1]), max(i, a[j-1]))
            v = (min(i, a[j]), max(i, a[j]))
            g[u].append(v)
    sv = TSort(g)
    if len(sv) != N*(N-1)//2:
        return -1
    
    dp = defaultdict(lambda:0)
    for u in sv:
        for v in g[u]:
            dp[v] = max(dp[v], dp[u]+1)
    return dp[sv[-1]] + 1


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv2(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s = Counter()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            s[n] += 1
    while True:
        c = 0
        dell = []
        adding = []
        for k, v in s.items():
            if v == 1:
                continue
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s.pop(k)
        for k in adding:
            s[k] += 1

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    while True:
        s = Counter()
        for i in range(1, N+1):
            if A[i-1]:
                d = A[i-1][-1]
                n = (min(i, d), max(i, d))
                s[n] += 1

        c = 0
        for k, v in s.items():
            if v == 1:
                continue
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            c += 1
        if c == 0:
            break
        else:
            ans += 1

    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    while True:
        t = []
        s = Counter()
        for i in range(1, N+1):
            if A[i-1]:
                n = (min(i, A[i-1][-1]), max(i, A[i-1][-1]))
                t.append(n)
                s[n] += 1

        c = 0
        for k, v in s.items():
            if v == 1:
                continue
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            c += 1
        if c == 0:
            break
        else:
            ans += 1

    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()

Buggy python submission (verdict: Time Limit Exceeded):
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    while True:
        t = []
        s = Counter()
        for i in range(1, N+1):
            if A[i-1]:
                n = (min(i, A[i-1][-1]), max(i, A[i-1][-1]))
                t.append(n)
                s[n] += 1

        c = 0
        for k, v in s.items():
            if v == 1:
                continue
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            c += 1
        if c == 0:
            break
        else:
            ans += 1

    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))


if __name__ == '__main__':
    main()


Fixed submission:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    ans = 0
    A = [list(reversed(a)) for a in A]

    s1 = set()
    s2 = set()
    for i in range(1, N+1):
        if A[i-1]:
            d = A[i-1][-1]
            n = (min(i, d), max(i, d))
            if n not in s1:
                s1.add(n)
            else:
                s2.add(n)
                s1.remove(n)
        
    while True:
        c = 0
        dell = []
        adding = []
        for k in s2:
            a, b = k
            A[a-1].pop()
            if A[a-1]:
                d = A[a-1][-1]
                n = (min(a, d), max(a, d))
                adding.append(n)
            A[b-1].pop()
            if A[b-1]:
                d = A[b-1][-1]
                n = (min(b, d), max(b, d))
                adding.append(n)
            dell.append(k)
            c += 1

        for k in dell:
            s2.remove(k)
        for k in adding:
            if k in s1:
                s2.add(k)
                s1.remove(k)
            else:
                s1.add(k)

        if c == 0:
            break
        else:
            ans += 1


    for a in A:
        if a:
            return -1
    return ans


def main():
    N = read_int()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, A))

    # N = 1000
    # A = []

    # while True:
    #     for i in range(1, N+1):
    #         t = list(range(1, N+1))
    #         t.remove(i)
    #         random.shuffle(t)
    #         A.append(t)
    #     print(slv(N, A))


if __name__ == '__main__':
    main()