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 (Python):
n = int(input())
a = [[] for i in range(n)]
for i in range(n):
    a[i] = list(map(int, input().split()))
    
ans = 0
nowlist = [a[i][0] for i in range(n)]
ans = 0
amap = [[0 for i in range(max(0,j))] for j in range(n+1)]
dokomade = [0 for i in range(n+1)]
todaylist = []
tomorrow = []

for i in range(n):
    i1 = min(nowlist[i],i+1)
    i2 = max(nowlist[i],i+1)
    amap[i2][i1] += 1
    if(amap[i2][i1]==2):
        todaylist.append([i1,i2])



while(True):
    for i in range(len(todaylist)):
        i1=todaylist[i][0]
        i2=todaylist[i][1]
        dokomade[i1]+=1
        dokomade[i2]+=1
        if(dokomade[i1]<n-1):
            temp1=i1
            temp2=a[i1-1][dokomade[i1]]
            i3=max(temp1,temp2)
            i4=min(temp1,temp2)
            amap[i3][i4]+=1
            if(amap[i3][i4]==2):
                tomorrow.append([i3,i4])
        if(dokomade[i2]<n-1):
            temp1=i2
            temp2=a[i2-1][dokomade[i2]]
            i3=max(temp1,temp2)
            i4=min(temp1,temp2)
            amap[i3][i4]+=1
            if(amap[i3][i4]==2):
                tomorrow.append([i3,i4])
    
    ans += 1
    
    if(len(tomorrow)==0):
        if(sum(dokomade)!= n*(n-1)):
            ans = -1
        break
    todaylist = tomorrow
    tomorrow=[]
    
print(ans)

Solution (Python):
N = int(input())
A = []
for i in range(N):
  As = list(map(int, input().split()))
  As = list(reversed(list(map(lambda a: a-1, As))))
  A.append(As)

d = 0
n = 0
l = list(range(N))
while True:
  n2 = 0
  l2 = []
  s2 = set()
  for i in l:
    if A[i] == []:
      continue
    j = A[i][-1]
    if A[j] == []:
      continue
    if i in s2 or j in s2:
      continue
    if A[j][-1] == i:
      n += 1
      n2 += 1
      s2.add(i)
      s2.add(j)
      l2.append(i)
      l2.append(j)
      A[i].pop()
      A[j].pop()
  if n2 == 0:
    if n == N*(N-1)//2:
      break
    print(-1)
    exit()
  l = l2
  d += 1
print(d)

Solution (Python):
from collections import defaultdict

class Solution:
    def main(self):
        N = int(input())
        A = []
        for i in range(N):
            a = list(map(lambda x: int(x)-1, input().split())) + [-1]
            A.append(a)

        hashmap = defaultdict(set)
        for i in range(N):
            hashmap[A[i][0]].add(i)

        

        cnt = 0
        old_cnt = 0
        checklist = set(range(N))

        for day in range(1, N*(N-1)+1):
            cands = set()
            for i in checklist:
                if i in hashmap and A[i][0] in hashmap[i]:
                    if i < A[i][0]:
                        cands.add((i, A[i][0]))
                    else:
                        cands.add((A[i][0], i))

            for x, y in cands:
                
                hashmap[y].remove(x)
                hashmap[x].remove(y)
                hashmap[A[x][1]].add(x)
                hashmap[A[y][1]].add(y)
                A[x].pop(0)
                A[y].pop(0)
                cnt += 1

            if cnt == N*(N-1)//2:
                print(day)
                break
            elif cnt == old_cnt:
                print(-1)
                break
            else:
                old_cnt = cnt
                checklist = set().union(*cands)
                
                


if __name__ == '__main__':
    Solution().main()

Solution (Python):
from collections import deque

N = int(input())
A = [list(map(int, input().split()))[::-1] for _ in range(N)]


l = [[0 for _ in range(N+1)] for _ in range(N+1)]
day = 0
q = deque([(i+1, a.pop()) for i, a in enumerate(A)])

while q:
    day += 1
    r = deque()
    while q:
        p = q.popleft()
        
        
        
        
        
        x, y = p
        if x > y:
            x, y = y, x
        l[x][y] += 1
        if l[x][y] >= 2:
            l[x][y] -= 2
            if A[x-1]:
                r.append((x, A[x-1].pop()))
            if A[y-1]:
                r.append((y, A[y-1].pop()))
    q = r

if all(map(len, A)):
    print(-1)
else:
    print(day)

Solution (Python):

"""
Created on Sun Sep  1 21:55:48 2019

@author: Yamazaki Kenichi
"""


N = int(input())
A = [list(map(int,input().split())) for i in range(N)]

T = [0 for i in range(N)]
today = [True for i in range(N)]
yesterday = [i for i in range(N)]

ans = 0
counta = 0
while counta < N:
    today = set([])
    today_p = []
    for i in yesterday:
        if not i in today:
            vs = A[i][T[i]] - 1
            if A[vs][T[vs]] == i + 1 and not vs in today:
                T[i] += 1
                T[vs] += 1
                if T[i] == N - 1:
                    T[i] = 0
                    counta += 1
                if T[vs] == N - 1:
                    T[vs] = 0 
                    counta += 1
                today.add(i)
                today.add(vs)
                today_p.extend([i,vs])
    yesterday = today_p

    if len(today_p) == 0:
        ans = -1
        break
    ans += 1
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque
def main():
    N = int( input())
    A = [deque()] + [deque( map( int, input().split())) for _ in range(N)]
    Days = [0]*(N+1)
    NOW = [0]*(N+1)
    
    
    
    
    q = deque( [ i+1 for i in range(N)])
    while q:
        i = q.popleft()
        if not A[i]:
            continue
        a = A[i].popleft()
        if NOW[a] == i:
            Days[a] = Days[i] = max(Days[a], Days[i])+1
            q.append(i)
            q.append(a)
            NOW[a] = NOW[i] = 0
        else:
            NOW[i] = a
    for i in range(1,N+1):
        if A[i]:
            print(-1)
            return
    print( max(Days))
if __name__ == '__main__':
    main()

Solution (Python):

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))

    
    

    
    
    
    
    
    
    


if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]

new = []
wait = []
for i in range(n):
    new.append(i)
    wait.append(a[i][0])

progress = [0] * n
day = 0
finished = []
while len(finished) < n:
    visited = []
    for i in new:
        _wait = wait[i] - 1

        if _wait != float('inf') and wait[_wait] == i + 1 and _wait not in visited and i not in visited:
            progress[i] += 1
            progress[_wait] += 1
            visited.append(i)
            visited.append(_wait)

            if progress[i] != n - 1:
                wait[i] = a[i][progress[i]]
            else:
                wait[i] = float('inf')
                finished.append(i)

            if progress[_wait] != n - 1:
                wait[_wait] = a[_wait][progress[_wait]]
            else:
                wait[_wait] = float('inf')
                finished.append(_wait)

    
    if not visited:
        day = -1
        break

    new = []
    for i in range(len(visited)):
        new.append(visited[i])

    day += 1


print(day)

Solution (Python):
from collections import deque


def main():
    N = int(input())
    A = [deque(map(lambda x: int(x)-1, input().split())) for _ in range(N)]
    ans = 1
    empty = 0
    candidates = set(range(N))
    while True:
        used = set()
        for i in candidates:
            if len(A[i]) == 0 or i in used:
                continue
            j = A[i][0]
            if len(A[j]) and A[j][0] == i and j not in used:
                used.add(i)
                used.add(j)
                A[i].popleft()
                A[j].popleft()
                if len(A[i]) == 0:
                    empty += 1
                if len(A[j]) == 0:
                    empty += 1
        if empty == N:
            break
        if len(used) == 0:
            ans = -1
            break
        ans += 1
        candidates = used
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
ct=[0 for i in range(n)]
fin=0
day=0
count=0
check=[0,0]
while count!=n*(n-1)//2 and day<=10**4:
  L=[0 for i in range(n)]
  f1=0
  for i in range(n):
    if L[i]==0 and ct[i]!=n-1:
      x=l[i][ct[i]]
      if l[x-1][ct[x-1]]-1==i and L[x-1]==0:
        ct[i]+=1
        ct[x-1]+=1
        L[i]=1
        L[x-1]=1
        count+=1
  day+=1
  check[0]=check[1]
  check[1]=count
  if check[0]==check[1]:
    print(-1)
    sys.exit()
if day>10**4:
  print(n*(n-1)//2)
  sys.exit()
print(day)

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline
N = int(input())
A = [0] + [list(map(lambda x: tuple(sorted((i, int(x)))), input().split())) for i in range(1, N+1)]
Idx = [0]*(N+1)
pool = set()  
q = deque([a[0] for a in A[1:]])

ans = 1
s = set()
while q:
    
    p = q.popleft()
    if p in pool:
        pool.remove(p)
        a, b = p
        Idx[a] += 1
        Idx[b] += 1
        if a in s or b in s:
            ans += 1
            s = {a, b}
        else:
            s.add(a)
            s.add(b)
        if Idx[a]<N-1:
            q.append(A[a][Idx[a]])
        if Idx[b]<N-1:
            q.append(A[b][Idx[b]])
    else:
        pool.add(p)
if pool:
    print(-1)
else:
    print(ans)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007


def A():
    s = S()
    t = S()
    ans = 0
    for i in range(len(s)):
        if s[i] == t[i]:
            ans += 1
    print(ans)
    return


def B():
    a,b = LI()
    for i in range(10000):
        if 1+i*a-i >= b:
            print(i)
            return
    return


def C():
    n = I()
    a = LI()
    ans = 0
    r = 1
    for l in range(n):
        if r == l:
            r += 1
        while r < n and a[r-1] >= a[r]:
            r += 1
        ans = max(ans, r-l-1)
    print(ans)
    return


def D():
    n = I()
    print(n*(n-1)>>1)
    return


def E():
    def dfs(x,p):
        if dp[x] != None:
            return dp[x]
        dp[x] = -1
        for y in v[x]:
            if p[y]:
                dp[x] = float("inf")
                break
            p[y] = 1
            dp[x] = max(dp[x], dfs(y,p)+1)
            p[y] = 0
        return dp[x]

    n = I()
    a = LIR(n)
    for i in range(n):
        for j in range(n-1):
            a[i][j] -= 1
    m = n*(n-1)
    v = [[] for i in range(m)]
    for i in range(n):
        p = n*min(i, a[i][0]) + max(i, a[i][0])
        for j in range(n-2):
            p_ = n*min(i, a[i][j+1]) + max(i, a[i][j+1])
            v[p_].append(p)
            p = p_
    dp = defaultdict(lambda : None)
    for i in range(m):
        if not v[i]:
            dp[i] = 1
    ans = 1
    p = [0]*m
    for x in range(m):
        p[x] = 1
        if ans < dfs(x,p):
            ans = dp[x]
        p[x] = 0
    if ans == float("inf"):
        print(-1)
    else:
        print(ans)
    return


def F():
    n = I()
    p = LIR(n)

    return


if __name__ == "__main__":
    E()

Solution (Python):
from collections import defaultdict, deque, Counter
import sys
import heapq
import math



sys.setrecursionlimit(1000000000)

MIN = -10 ** 9
MOD = 10 ** 9 + 7


def main():
    N = int(input())
    
    
    A = {
        i: list(reversed([int(a) - 1 for a in input().split()]))
        for i in range(N)
    }

    Q = set(range(N))

    count = 0
    while True:
        pool = []
        for i in Q:
            ai = A[i]
            if len(ai) == 0:
                continue
            target = ai[-1]
            
            
            target_q = A[target]
            if target_q[-1] == i:
                
                pool.append(i)
                pool.append(target)

        if len(pool) == 0:
            if len(Q) != 0:
                print(-1)
                return
            else:
                raise ValueError("test")

        qq = []
        for i in set(pool):
            A[i].pop()
            if len(A[i]) != 0:
                qq.append(i)
        Q = set(qq)

        count += 1
        if len(Q) == 0:
            print(count)
            return


if __name__ == '__main__':
    main()

Solution (Python):
def solve_e(n, a_list):
    days = 0
    ind_list = [0] * n
    match_count = 0
    queue = list(range(n))
    stack = dict()
    while len(queue) > 0:
        days += 1
        new_queue = []
        for p in queue:
            if ind_list[p] < n - 1:
                q = a_list[p][ind_list[p]] - 1
                k = str(min(p, q)) + "_" + str(max(p, q))
                if k in stack.keys():
                    ind_list[p] += 1
                    ind_list[q] += 1
                    
                    new_queue.append(p)
                    new_queue.append(q)
                    match_count += 1
                else:
                    stack[k] = 1
        queue = new_queue
    if match_count == n * (n - 1) // 2:
        return days - 1
    else:
        return -1


def test():
    N = 1000
    A_list = []
    for i in range(N):
        A_list.append(list(range(1, i + 1)) + list(range(i + 2, N + 1)))
    print(solve_e(N, A_list))


def main():
    N = int(input())
    A_list = []
    for _ in range(N):
        A_list.append(list(map(int, input().split())))
    print(solve_e(N, A_list))


if __name__ == "__main__":
    main()

Solution (Python):
N=int(input())
A=[list(map(int,input().split())) for _ in range(N)]

inds=[[-1]*N for _ in range(N)]
cnt=0
for i in range(N):
    for j in range(i+1,N):
        inds[i][j]=cnt
        cnt+=1

NN=(N*(N-1))//2
edges=[[] for _ in range(NN)]
nums = [0]*NN

for i in range(N):
    sis=[0]*(N-1)
    for j in range(N-1):
        src, dst = sorted([i,A[i][j]-1])
        sis[j] = inds[src][dst]

    for src,dst in zip(sis[:-1],sis[1:]):
        edges[src].append(dst)
        nums[dst]+=1

arr = [i for i,n in enumerate(nums) if n==0]

ans=0
cnt=0
while len(arr)>0:
    ans+=1
    cnt+=len(arr)
    narr=[]
    for src in arr:
        for dst in edges[src]:
            nums[dst]-=1
            if nums[dst]==0:
                narr.append(dst)
    arr=narr

if cnt < NN:
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque

n = int(input())
a = ["dummy!"] + [list(map(int, input().split())) for _ in range(n)]
t = 0
f = 1
cur = [0]*(n+1)
date = [0]*(n+1)
seed = deque()
for i in range(1,n+1):
    op = a[i][cur[i]]
    if a[op][cur[op]] == i:
        seed.append((i,op))
        cur[i] += 1
        cur[op] += 1
        date[i] = date[op] = max(date[i],date[op]) + 1
while seed:
    p,q = seed.popleft()   
    for i in p,q:
        if cur[i] >= n-1:
            continue
        op = a[i][cur[i]]
        if a[op][cur[op]] == i:
            seed.append((i,op))
            cur[i] += 1
            cur[op] += 1
            date[i] = date[op] = max(date[i],date[op]) + 1
if any(x < n-1 for x in cur[1:]):
    print(-1)
else:
    print(max(date))

Solution (Python):
def solve():
    N = int(input())
    Ass = []
    for _ in range(N):
        As = list(map(lambda x: int(x)-1, input().split()))
        Ass.append(As+[N])

    games = []
    numReadyss = [[0]*(N) for _ in range(N)]
    iAs = [0] * N
    for i in range(N):
        j = Ass[i][iAs[i]]
        if j > i: i, j = j, i
        numReadyss[i][j] += 1
        if numReadyss[i][j] >= 2:
            games.append((i, j))
    ans = 1
    numOK = 0
    while True:
        if not games:
            print(-1)
            return
        game2s = []
        for i, j in games:
            iAs[i] += 1
            i2 = Ass[i][iAs[i]]
            if i2 == N:
                numOK += 1
            else:
                if i2 > i: i, i2 = i2, i
                numReadyss[i][i2] += 1
                if numReadyss[i][i2] >= 2:
                    game2s.append((i, i2))
            iAs[j] += 1
            j2 = Ass[j][iAs[j]]
            if j2 == N:
                numOK += 1
            else:
                if j2 > j: j, j2 = j2, j
                numReadyss[j][j2] += 1
                if numReadyss[j][j2] >= 2:
                    game2s.append((j, j2))
        if numOK >= N:
            print(ans)
            return
        ans += 1
        games = game2s


solve()

Solution (Python):
N = int(input())

from collections import defaultdict,deque

A = [list(map(int,input().split())) for i in range(N)]

count = 0
B = defaultdict(int)
now_list = [0]*N
day=0

Q = deque([i for i in range(N)])
while count<(N*(N-1))//2:
        Q2 = deque([])
        battle_flag=False
        while len(Q)>0:
                i = Q.popleft()
                j = A[i][now_list[i]]-1
                a=min(i,j)
                b=max(i,j)
                if B[str(a)+" "+str(b)]==1:
                        count+=1
                        B[str(a)+" "+str(b)]=0
                        now_list[i]+=1
                        now_list[j]+=1
                        if now_list[i]<N-1:
                                Q2.append(i)                                
                        if now_list[j]<N-1:
                                Q2.append(j)                                
                        battle_flag=True
                else:
                        B[str(a)+" "+str(b)]+=1
        if not battle_flag:
                break
        Q = Q2
        day+=1

if count==(N*(N-1))//2:
        print(day)
else:
        print(-1)

Solution (Python):
n=int(input())
a=[]
l=[[] for i in range(n)]
ind=[0 for i in range(n)]
s=set()
ans=1
from collections import deque
q=deque([])
for i in range(n):
    tmp=[int(j)-1 for j in input().split()]
    a.append(tmp)
    for j in tmp:
        if i<j:
            l[i].append((i,j))
        else:
            l[i].append((j,i))
    q.append(l[i][0])
ll=[]
while q:
    p=q.popleft()
    if p in s:
        s.remove(p)
        i,j=p
        if i in ll or j in ll:
            ans+=1
            ll=[i,j]
        else:
            ll.append(i)
            ll.append(j)
        if ind[i]<n-2:
            ind[i]+=1
            q.append(l[i][ind[i]])
        if ind[j]<n-2:
            ind[j]+=1
            q.append(l[j][ind[j]])
    else:
        s.add(p)

for i in range(n):
    if ind[i]!=n-2:
        print(-1)
        exit()
print(ans)

Solution (Python):
N = int(input())
X = [[int(a)-1 for a in input().split()] for _ in range(N)]
Y = [0] * N
Z = [-1] * N

L = [a for a in range(N)]
f = 1
d = 0
c = 0
while f:
    d += 1
    f = 0
    NL = []
    for l in L:
        a, aa = Y[l], Z[l]
        if a >= N - 1: continue
        ll = X[l][a]
        b, bb = Y[ll], Z[ll]
        if b >= N - 1: continue
        lll = X[ll][b]
        if lll == l and aa < d and bb < d:
            f = 1
            c += 1
            Y[l] += 1
            Z[l] = d
            if Y[l] < N - 1: NL.append(l)
            Y[ll] += 1
            Z[ll] = d
            if Y[ll] < N - 1: NL.append(ll)
    if c == N*(N-1)//2:
        print(d)
        break
    L = NL
else:
    print(-1)

Solution (Python):
N = int(input())
X = [[int(a)-1 for a in input().split()] for _ in range(N)]
Y = [0] * N
Z = [-1] * N

L = [a for a in range(N)]
f = 1
d = 0
c = 0
while f:
    d += 1
    f = 0
    NL = []
    for l in L:
        a, aa = Y[l], Z[l]
        if a >= N - 1: continue
        ll = X[l][a]
        b, bb = Y[ll], Z[ll]
        if b >= N - 1: continue
        lll = X[ll][b]
        if lll == l and aa < d and bb < d:
            f = 1
            c += 1
            Y[l] += 1
            Z[l] = d
            if Y[l] < N - 1: NL.append(l)
            Y[ll] += 1
            Z[ll] = d
            if Y[ll] < N - 1: NL.append(ll)
    if c == N*(N-1)//2:
        print(d)
        break
    L = NL
else:
    print(-1)

Solution (Python):
N = int(input())
A = [list(map(int, input().split())) for _ in range(N)]    

cnt = [0] * N

S = []
for i in range(N):
  t = A[i][cnt[i]] - 1
  if i == A[t][cnt[t]] - 1:
    if cnt[i] != N - 2:
      S.append(i)

ans = 1
L = [True] * N
while S:
  ans += 1
  for i in S:
    cnt[i] += 1
    L[i] = True
  T = []
  for i in S:
    if L[i]:
      t = A[i][cnt[i]] - 1
      if i == A[t][cnt[t]] - 1:
        if cnt[i] != N - 2:
          L[i] = False
          T.append(i)
        if L[t]:
          L[t] = False
          if cnt[t] != N - 2:
            T.append(t)
  S = T

for i in range(N):
  if cnt[i] != N - 2:
    print(-1)
    break
else:
  print(ans)

Solution (Python):
from collections import defaultdict

N = int(input())
A = [list(map(lambda x:int(x)-1,input().split()))[::-1] for _ in range(N)]
d = defaultdict(lambda:0)
q = []
for i in range(N):
    j = A[i].pop()
    i,j = min(i,j),max(i,j)
    d[(i,j)] += 1
    if d[(i,j)] == 2:
        q.append((i,j))

ans = 0
while q:
    ans += 1
    q_ = []
    for i,j in q:
        if A[i]:
            i_ = A[i].pop()
            i,i_ = min(i,i_),max(i,i_)
            d[(i,i_)] += 1
            if d[(i,i_)] == 2:
                q_.append((i,i_))
        if A[j]:
            j_ = A[j].pop()
            j,j_ = min(j,j_),max(j,j_)
            d[(j,j_)] += 1
            if d[(j,j_)] == 2:
                q_.append((j,j_))
    q = q_

f = True
for i in range(N):
    if A[i]:
        f = False

if f:
    print(ans)
else:
    print(-1)

Solution (Python):



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

n = int(input())
a = [[min(i,int(j)-1)+max(i,int(j)-1)*(max(i,int(j)-1)-1)//2 for j in readline().split()] for i in range(n)]

N =n*(n-1)//2

g = [[] for i in range(N)]
p = [[] for i in range(N)]

for i in range(n):
    for j in range(n-2):
        g[a[i][j]].append(a[i][j+1])
        p[a[i][j+1]].append(a[i][j])
        



ans = [0]*(N)

indegree = [len(v) for v in p] 
Source = [i for i, c in enumerate(indegree) if c == 0] 

num = 0
while Source:
    node = Source.pop()
    
    num += 1
    for child in g[node]:
        indegree[child] -= 1 
        if ans[child] < ans[node]+1: ans[child] = ans[node]+1     
        if indegree[child] == 0:
            Source.append(child)


if num != N:
    print(-1)
else:
    print(max(ans)+1)

Solution (Python):
from collections import Counter
N = int(input())
Ass = [list(map(int, input().split())) for _ in range(N)]
ct = Counter()
q = set([(i, 0) for i in range(N)])
idxs = [0] * N
n = 0
ans = 0
while q:
  nq = set()
  for i, k in q:
    a = i+1
    b = Ass[i][k]
    if a > b: a, b = b, a
    ct[(a, b)] += 1
    if ct[(a, b)] == 2:
      n += 1
      idxs[a-1] += 1
      if idxs[a-1] < N-1:
        nq.add((a-1, idxs[a-1]))
      idxs[b-1] += 1
      if idxs[b-1] < N-1:
        nq.add((b-1, idxs[b-1]))
  ans += 1
  q = nq
if n == N * (N-1) // 2:
  print(ans)
else:
  print(-1)

Solution (Python):
from collections import deque

def solve():
    n = int(input())
    a = []
    for i in range(n):
        ai = [int(j)-1 for j in input().split()]
        a.append(deque(ai))

    d = set()
    
    q = deque()
    for i in range(n):
        ai = a[i].popleft()
        if i < ai:
            q.append((i, ai))
        else:
            q.append((ai, i))

    ans = 0
    while q:
        ans += 1
        nxt_q = deque()
        while q:
            i, ai = q.pop()
            if (i, ai) in d:
                if a[i]:
                    ni = a[i].popleft()
                    if i < ni:
                        nxt_q.append((i, ni))
                    else:
                        nxt_q.append((ni, i))
                if a[ai]:
                    ni = a[ai].popleft()
                    if ai < ni:
                        nxt_q.append((ai, ni))
                    else:
                        nxt_q.append((ni, ai))
            else:
                d.add((i, ai))
        q = nxt_q

    
    if any(i for i in a):
        ans = -1
    print(ans)

if __name__ == "__main__":
    solve()

Solution (Python):
import sys
readline = sys.stdin.readline
from collections import deque
N = int(readline())
G = [[] for i in range(N*N)]
deg = [0]*(N*N)
day = [0]*(N*N)
F = set()
for p in range(N):
    *A, = map(int, readline().split())
    for k in range(N-1):
        A[k] -= 1
    for k in range(N-2):
        i = A[k]+p*N if A[k] < p else p+A[k]*N
        j = A[k+1]+p*N if A[k+1] < p else p+A[k+1]*N
        G[i].append(j)
        deg[j] += 1
    i = A[0]+p*N if A[0] < p else p+A[0]*N
    F.add(i)
que = deque()
for i in F:
    if deg[i] == 0:
        que.append(i)
        day[i] = 1
rest = N*(N-1)//2
while que:
    v = que.popleft()
    rest -= 1
    d = day[v]
    for w in G[v]:
        deg[w] -= 1
        if deg[w] == 0:
            day[w] = day[v] + 1
            que.append(w)
if rest > 0:
    print(-1)
else:
    print(max(day))

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

N = int(input())
A = [[-1] + [int(x)-1 for x in row.split()][::-1] for row in sys.stdin.readlines()]

A.append([-1])

def f(cand):
    cand1 = set()
    can_use = []
    for n in cand:
        if A[A[n][-1]][-1] == n:
            can_use.append(n)
    for n in can_use:
        A[n].pop()
        cand1.add(n)
        if A[n][-1] != -1:
            cand1.add(A[n][-1])
    return len(can_use),cand1

answer = 0
rest = N*(N-1)
cand = set(range(N))
while True:
    answer += 1
    x,cand = f(cand)
    if x == 0:
        answer = -1
        break
    rest -= x
    if rest == 0:
        break

print(answer)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

N = int(input())
A = [[-1] + [int(x)-1 for x in row.split()][::-1] for row in sys.stdin.readlines()]

A.append([-1])

def f(cand):
    cand1 = set()
    can_use = []
    for n in cand:
        if A[A[n][-1]][-1] == n:
            can_use.append(n)
    for n in can_use:
        A[n].pop()
        cand1.add(n)
        if A[n][-1] != -1:
            cand1.add(A[n][-1])
    return len(can_use),cand1

answer = 0
rest = N*(N-1)
cand = set(range(N))
while True:
    answer += 1
    x,cand = f(cand)
    if x == 0:
        answer = -1
        break
    rest -= x
    if rest == 0:
        break

print(answer)

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline
N = int(input())
A = [0] + [list(map(lambda x: tuple(sorted((i, int(x)))), input().split())) for i in range(1, N+1)]
Idx = [0]*(N+1)
pool = set()  
q = deque([a[0] for a in A[1:]])

ans = 1
s = set()
while q:
    
    p = q.popleft()
    if p in pool:
        pool.remove(p)
        a, b = p
        Idx[a] += 1
        Idx[b] += 1
        if a in s or b in s:
            ans += 1
            s = {a, b}
        else:
            s.add(a)
            s.add(b)
        if Idx[a]<N-1:
            q.append(A[a][Idx[a]])
        if Idx[b]<N-1:
            q.append(A[b][Idx[b]])
    else:
        pool.add(p)
if pool:
    print(-1)
else:
    print(ans)