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):
def main():
    from collections import defaultdict,deque
    from itertools import count
    (n,),*a=[list(map(int,t.split()))for t in open(0)]
    d=defaultdict(count().__next__)
    es=[]
    for i,b in enumerate(a,1):
        for j,k in zip(b,b[1:]):
            x,y=i,j
            if y<x:x,y=y,x
            v,w=i,k
            if w<v:v,w=w,v
            es+=(d[x*n+y],d[v*n+w]),
    s=len(d)
    outs=[[]for _ in range(s)]
    ins=[0]*s
    f=set(range(s))
    for i,j in es:
        outs[i]+=j,
        f-={j}
        ins[j]+=1
    q=deque(f)
    r=[]
    data=[0]*s
    m=0
    while q:
        i=q.popleft()
        r+=i,
        t=data[i]+1
        if t>m:m=t
        for j in outs[i]:
            ins[j]-=1
            if ins[j]<1:q+=j,
            if t>data[j]:data[j]=t
    print(-(len(r)<s)or m)
main()

Solution (Python):
n = int(input())
a = [[] for i in range(n)]
for i in range(n):
    a[i] = list(map(int,input().split()))
    for j in range(n-1):
        a[i][j] -= 1
    a[i].reverse()
q = []

def check(i):
    if len(a[i]) == 0:
        return 
    j = a[i][-1]
    if len(a[j]) == 0:
        return
    if a[j][-1] == i:
        q.append([min(i,j), max(i,j)])
for i in range(n):
    check(i)
day = 0
while (len(q) > 0):
    day += 1
    prevQ = list(map(list, set(map(tuple, q))))
    q = []
    for i,j in prevQ:
        a[i].pop()
        a[j].pop()
        check(i)
        check(j)
for i in range(n):
    if len(a[i]) > 0:
        print(-1)
        exit()
print(day)

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

def can_match(i, A, next_set):
	if not A[i]:
		return
	j = A[i][-1]
	if A[j][-1] == i:
		if i < j:
			next_set.add((i, j))
		else:
			next_set.add((j, i))
		
 
next_set = set()
for i in range(N):
	can_match(i, A, next_set)
 
day = 0
battle = 0
while next_set:
	day += 1
	current_set = next_set.copy()
	next_set = set()
	for match in current_set:
		battle += 1
		del A[match[0]][-1]
		can_match(match[0], A, next_set)
		del A[match[1]][-1]
		can_match(match[1], A, next_set)
 
if battle == N*(N-1) // 2:
	print(day)
    
else:
	print(-1)

Solution (Python):
n = int(input())
 
a = {i+1: list(map(int, input().split())) for i in range(n)}
ret = 1
pair = []
keys = a.keys()
while True:
    for k in keys:
        v = a[k][0]
        if a[v][0] == k:
            pair.append(k)
            if v not in keys:
                pair.append(v)
    for p in pair:
        if len(a[p]) > 1:
            a[p] = a[p][1:]
        else:
            a.pop(p)
    if len(a) == 0:
        break
    if len(pair) == 0:
        ret = -1
        break
    ret = ret + 1
    keys = [k for k in pair if k in a]
    pair = []
 
print(ret)

Solution (Python):
import sys
from collections import deque

input = sys.stdin.readline

n = int(input())

to_battle_with = [deque([i - 1 for i in map(int, input().split())]) for _ in range(n)]


def update_battle(player, battle_set, to_battle_with):
    if not to_battle_with[player]:
        return
    next_opponent = to_battle_with[player][0]
    if not to_battle_with[next_opponent]:
        return
    if to_battle_with[next_opponent][0] == player:
        if player > next_opponent:
            player, next_opponent = next_opponent, player
        battle_set.add((player, next_opponent))


battles_today = set()
for player in range(n):
    update_battle(player, battles_today, to_battle_with)

day_count = 0
battle_count = 0
num_all_battles = (n * (n - 1)) // 2

while battles_today:
    battles_tomorrow = set()
    for p1, p2 in battles_today:
        battle_count += 1
        to_battle_with[p1].popleft()
        to_battle_with[p2].popleft()
        for p in [p1, p2]:
            update_battle(p, battles_tomorrow, to_battle_with)
    battles_today = battles_tomorrow
    day_count += 1

if battle_count == num_all_battles:
    print(day_count)
else:
    print(-1)

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

MAXN = 1005
MAXV = MAXN*(MAXN-1)//2
to = [[] for _ in range(MAXV)] 
id = [[[] for _ in range(MAXN)] for _ in range(MAXN)] 
def toId(i,j): 
    if i > j: 
        i,j = j,i
    return id[i][j]

visited = [False]*MAXV
calculated = [False]*MAXV
dp = [1]*MAXV 

def dfs(v):
    if visited[v]:
        if not calculated[v]:
            return -1 
        return dp[v]
    visited[v] = True
    for u in to[v]: 
        res = dfs(u)
        if res == -1: return -1 
        dp[v] = max(dp[v], res+1)
    calculated[v] = True
    return dp[v]

def main():
    n = int(input())
    a = [[int(i) for i in readline().split()] for _ in range(n)]
    for i in range(n):
        for j in range(n-1):
            a[i][j] -= 1 
    V = 0
    for i in range(n):
        for j in range(n):
            if i < j:
                id[i][j] = V
                V += 1 
    for i in range(n):
        for j in range(n-1):
            a[i][j] = toId(i,a[i][j]) 
        for j in range(n-2): 
            to[a[i][j+1]].append(a[i][j])
    ans = 0
    for i in range(V):
        res = dfs(i)
        if res == -1:
            print('-1') 
            return
        ans = max(ans, res)
    print(ans)
    return

if __name__ == '__main__':
    main()

Solution (Python):
def list_up_next_games(players):
    games = set()
    for p in players:
        if A[p]:
            opponent = A[p][-1] - 1
            if A[opponent][-1] - 1 == p:
                if p < opponent:
                    games.add((p, opponent))
                else:
                    games.add((opponent, p))
    return(games)

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

games = list_up_next_games(list(range(N)))

done_games = []
days = 0
while games:
    days += 1
    players = []
    for game in games:
        done_games.append(game)
        A[game[0]].pop()
        A[game[1]].pop()
        players.append(game[0])
        players.append(game[1])
    games = list_up_next_games(players)

if len(done_games) == N*(N-1)//2:
    print(days)
else:
    print(-1)

Solution (Python):
def resolve():
    n = int(input())
    a = []

    for i in range(n):
        row = list(map(lambda x: int(x) - 1, input().split()))
        row.reverse()
        a.append(row)

    q = set()

    def check(i):
        if len(a[i]) == 0:
            return
        j = a[i][-1]
        if i == a[j][-1]:
            p = (i, j) if i < j else (j, i)
            q.add(p)

    for i in range(n):
        check(i)

    day = 0
    while len(q) > 0:
        day += 1
        prev_q, q = q, set()

        for p in prev_q:
            (i, j) = p
            a[i].pop()
            a[j].pop()

        for p in prev_q:
            (i, j) = p
            check(i)
            check(j)

    for i in range(n):
        if len(a[i]) != 0:
            print(-1)
            return
    print(day)
    
resolve()

Solution (Python):
n = int(input())
lst = [list(map(int, input().split())) for _ in range(n)]
 
current = []
for i in range(n):
    current.append(lst[i].pop(0))

count = 0
players = set(range(1, n+1))
while True:
    index_lst = []
    for i in players:
        candidate = current[i-1]
        if candidate in index_lst:
            continue
        if current[candidate-1] == i:
            index_lst += [i, candidate]   
    if len(index_lst) == 0:
        if sum(current) == 0:
            print(count)
            break
        else:
            print(-1)
            break
    for i in index_lst:
        if len(lst[i-1]) == 0:
            current[i-1] = 0
        else:
            current[i-1] = lst[i-1].pop(0)
    players = set(index_lst)
    count += 1

Solution (Python):
from collections import deque
 
n = int(input())
lst = [deque(map(int, input().split())) for _ in range(n)]
 
current = []
for i in range(n):
    current.append(lst[i].popleft())

count = 0
players = set(range(1, n+1))
while True:
    index_lst = []
    for i in players:
        candidate = current[i-1]
        if candidate in index_lst:
            continue
        if current[candidate-1] == i:
            index_lst += [i, candidate]   
    if len(index_lst) == 0:
        if sum(current) == 0:
            print(count)
            break
        else:
            print(-1)
            break
    for i in index_lst:
        if len(lst[i-1]) == 0:
            current[i-1] = 0
        else:
            current[i-1] = lst[i-1].popleft()
    players = set(index_lst)
    count += 1

Solution (Python):
N = int(input())
A = [[int(x) - 1 for x in input().split()] for _ in range(N)]

id = [[0] * N for _ in range(N)]
V = 0
to = []
for i in range(N):
    for j in range(i+1, N):
        id[i][j] = V
        V += 1
        to.append([])

def toId(i, j):
    if i > j:
        i, j = j, i
    return id[i][j]

for i in range(N):
    for j in range(N - 1):
        A[i][j] = toId(i, A[i][j])
    for j in range(N - 2):
        to[A[i][j+1]].append(A[i][j])

visited = [False] * V
calculated = [False] * V
dp = [0] * V
def dfs(v):
    if visited[v]:
        if not calculated[v]:
            return -1
        return dp[v]
    visited[v] = True
    dp[v] = 1
    for u in to[v]:
        res = dfs(u)
        if res == -1:
            return -1
        dp[v] = max(dp[v], res + 1)
    calculated[v] = True
    return dp[v]

ans = 0
for i in range(V):
    res = dfs(i)
    if res == -1:
        ans = -1
        break
    ans = max(ans, res)

print(ans)

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

def can_match(i, A, next_set):
	if not A[i]:
		return
	j = A[i][-1]
	if A[j][-1] == i:
		if i < j:
			next_set.add((i, j))
		else:
			next_set.add((j, i))

next_set = set()
for i in range(N):
	can_match(i, A, next_set)

day = 0
battle = 0
while next_set:
	day += 1
	current_set = next_set.copy()
	next_set = set()
	for match in current_set:
		battle += 1
		del A[match[0]][-1]
		can_match(match[0], A, next_set)
		del A[match[1]][-1]
		can_match(match[1], A, next_set)

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

Solution (Python):
from collections import deque

n = int(input())
a = [0] + list(deque(map(int, input().split())) for _ in range(n))
cnt, cur, days = 0, [0] * (n + 1), [0] * (n + 1)
q = deque(list(range(1, n + 1)))
while q:
	x = q.popleft()
	if not a[x]:
		continue
	y = a[x].popleft()
	if cur[y] == x:
		cnt += 1
		days[x] = days[y] = max(days[x], days[y]) + 1
		cur[x], cur[y] = 0, 0
		q.append(x)
		q.append(y)
	else:
		cur[x] = y
res = max(days) if cnt == n * (n - 1) // 2 else -1
print(res)

Solution (Python):
import sys

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

n = int(input())
graph = [list() for _ in range(n**2)]

id_index = [[i+j*n for i in range(n)] for j in range(n)]
index_list = []

def toId(p, o):
    if p > o:
        index = id_index[o][p]
        index_list.append(index)
        return index
    else: return id_index[p][o]

v_len = [-1 for _ in range(n)] * n
finished = [False for _ in range(n)] * n

def dfs(id):
    next_list = graph[id]

    if v_len[id] != -1:
        if not finished[id]:
            print(-1)
            sys.exit()
        return v_len[id]

    v_len[id] = 1

    for next in next_list:
        v_len[id] = max(v_len[id], dfs(next)+1)

    finished[id] = True
    return v_len[id]

for p in range(n):
    a = [toId(p, int(x)-1) for x in input().split()]
    for i in range(n-2):
        graph[a[i]].append(a[i+1])
    
ans = 0

for id in index_list:
    ans = max(dfs(id), ans)

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())

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

def can_match(i, A, next_set):
    if not A[i]: 
        return
    j = A[i][-1] 

    if A[j][-1] == i: 
        if i < j: 
            next_set.add((i,j))
        else: 
            next_set.add((j,i))


next_set = set() 
for i in range(N):
    can_match(i, A, next_set)


day = 0
battle = 0
while next_set:
    day += 1
    current_set, next_set = next_set, set()
    for match in current_set:
        battle += 1
        del A[match[0]][-1]
        can_match(match[0], A, next_set)
        del A[match[1]][-1]
        can_match(match[1], A, next_set)

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

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
A = [[x-1 for x in list(map(int, input().split()))[::-1]] for _ in range(N)]

def can_match(i, A, next_set):
  if not A[i]:
    return
  j = A[i][-1]
  if A[j][-1] == i:
    if i < j:
      next_set.add((i,j))
    else:
      next_set.add((j,i))
      
next_set = set()
for i in range(N):
  can_match(i, A, next_set)
  
day = 0
battle = 0
while next_set:
  day += 1
  current_set, next_set = next_set, set()
  for match in current_set:
    battle += 1
    del A[match[0]][-1]
    can_match(match[0], A, next_set)
    del A[match[1]][-1]
    can_match(match[1], A, next_set)
    
if battle == N*(N-1)//2:
  print(day)
else:
  print(-1)

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

def can_match(i, A, next_set):
  if not A[i]:
    return
  j = A[i][-1]
  if A[j][-1] == i:
    if i < j:
      next_set.add((i,j))
    else:
      next_set.add((j,i))
      
next_set = set()
for i in range(N):
  can_match(i, A, next_set)
  
day = 0
battle = 0
while next_set:
  day += 1
  current_set, next_set = next_set, set()
  for match in current_set:
    battle += 1
    del A[match[0]][-1]
    can_match(match[0], A, next_set)
    del A[match[1]][-1]
    can_match(match[1], A, next_set)
    
if battle == N*(N-1)//2:
  print(day)
else:
  print(-1)

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

def can_match(i, A, next_set):
  if not A[i]:
    return
  j = A[i][-1]
  if A[j][-1] == i:
    if i < j:
      next_set.add((i,j))
    else:
      next_set.add((j,i))
      
next_set = set()
for i in range(N):
  can_match(i, A, next_set)
  
day = 0
battle = 0
while next_set:
  day += 1
  current_set, next_set = next_set.copy(), set()
  for match in current_set:
    battle += 1
    del A[match[0]][-1]
    can_match(match[0], A, next_set)
    del A[match[1]][-1]
    can_match(match[1], A, next_set)
    
if battle == N*(N-1)//2:
  print(day)
else:
  print(-1)

Solution (Python):

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


def can_match(i, A, next_set):
  if not A[i]:
    return
  j = A[i][-1]
  if A[j][-1] == i:
    if i < j:
      next_set.add((i,j))
    else:
      next_set.add((j,i))

      
next_set = set()
for i in range(N):
  can_match(i, A, next_set)
  
day = 0
battle = 0
while next_set:
  day += 1
  current_set = next_set.copy()
  next_set = set()
  for match in current_set:
    battle += 1
    del A[match[0]][-1]
    can_match(match[0], A, next_set)
    del A[match[1]][-1]
    can_match(match[1], A, next_set)
if battle == N*(N-1)//2:
  print(day)
else:
  print(-1)

Solution (Python):
def f_e():
    n = int(input())
    a = [list(map(lambda x: int(x)-1, input().split()))[::-1] for _ in range(n)]
    q, bench, days = list(range(n)), [-1]*n, [0]*n
    while q:
        i = q.pop(0)
        if not a[i]:
            continue
        you = a[i].pop()
        if bench[you] == i:
            days[i] = days[you] = max(days[i], days[you])+1
            bench[i] = bench[you] = -1
            q.append(i); q.append(you)
        else:
            bench[i] = you
    o = -1 if max(bench)>=0 else max(days)
    print(o)

if __name__ == "__main__":
    f_e()

Solution (Python):
from collections import deque

if __name__ == '__main__':
    N = int(input())
    matches = [[int(x) - 1 for x in input().split()] for _ in range(N)]
    q = deque(range(N))
    days = [0] * N
    pairs = [-1] * N
    while q:
        a = q.popleft()
        match = matches[a]
        if not match:
            continue
        b = match.pop(0)
        if pairs[b] == a:
            days[a] = days[b] = max(days[a], days[b]) + 1
            q.append(a)
            q.append(b)
        else:
            pairs[a] = b
    print(max(days) if not any(matches) else -1)

Solution (Python):
import copy
import collections

N = int(input())
A=[]
for j in range(N): 
    A.append(collections.deque(int(i) for i in input().split()))

day = 0
empty = [0] * N 
s = [i for i in range(N)]


while N==N:
    
    q = []
    day +=1
    for i in s:
        
        
        
        if len(A[i]) == 0:
            empty[i] = None
        
        elif i in q:
            pass
        
        elif int(A[int(A[i][0])-1][0]) == i+1:
                
                q.append(i)
                q.append(int(A[i][0])-1)
                s = copy.copy(q)
    
    if len(q) == 0:
        if not(0 in empty):
            print(day-1)
            exit()
        else:
            print(-1)
            exit()
    
    
    else:
        for d in q:
            
            A[d].popleft()

Solution (Python):
N = int(input())
Ass = tuple(tuple(map(int, input().split())) for _ in range(N))
index = [0 for _ in range(N)]

Q = set(range(N))
ans = -1
while Q:
    ans += 1
    Q2 = Q.copy()
    Q.clear()
    for i in Q2:
        if index[i] >= N - 1:
            continue
        t = Ass[i][index[i]] - 1
        if Ass[t][index[t]] == i + 1:
            Q.add(i)
            Q.add(t)
    for i in Q:
        index[i] += 1

if min(index) < N - 1:
    print(-1)
else:
    print(ans)

Solution (Python):
N = int(input())
Ass = tuple(tuple(map(int, input().split())) for _ in range(N))
index = [0 for _ in range(N)]

Q = set(range(N))
ans = -1
while Q:
    ans += 1
    Q2 = Q.copy()
    Q.clear()
    for i in Q2:
        if index[i] >= N - 1:
            continue
        t = Ass[i][index[i]] - 1
        if Ass[t][index[t]] == i + 1:
            Q.add(i)
            Q.add(t)
    for i in Q:
        index[i] += 1

if min(index) < N - 1:
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque
 
N = int(input())
Ass = tuple(deque(map(int, input().split())) for _ in range(N))
 
Q = set(range(N))
ans = -1
while Q:
    ans += 1
    Q2 = Q.copy()
    Q.clear()
    for i in Q2:
        if not Ass[i]:
            continue
        t = Ass[i][0] - 1
        if Ass[t][0] == i + 1:
            Q.add(i)
            Q.add(t)
    for i in Q:
        Ass[i].popleft()

if any(Ass):
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque
 
N = int(input())
Ass = tuple(deque(map(int, input().split())) for _ in range(N))
 
Q = set(range(N))
ans = -1
while Q:
    ans += 1
    Q2 = Q.copy()
    Q.clear()
    for i in Q2:
        if Ass[i]:
            t = Ass[i][0] - 1
            if Ass[t][0] == i + 1:
                Q.add(i)
                Q.add(t)
    for i in Q:
        Ass[i].popleft()

if any(Ass):
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque
 
N = int(input())
Ass = tuple(deque(map(int, input().split())) for _ in range(N))
 
Q = set(range(N))
ans = -1
while Q:
    ans += 1
    Q2 = Q.copy()
    Q.clear()
    for i in Q2:
        if not Ass[i]:
            continue
        t = Ass[i][0] - 1
        if Ass[t][0] == i + 1:
            Q.add(i)
            Q.add(t)
    for i in Q:
        Ass[i].popleft()

if any(Ass):
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque
 
N = int(input())
Ass = tuple(deque(map(int, input().split())) for _ in range(N))
 
dp = [0 for _ in range(N)]
Q = set(range(N))
ans = -1
while Q:
    ans += 1
    Q2 = Q.copy()
    Q.clear()
    for i in Q2:
        if not Ass[i]:
            continue
        t = Ass[i][0] - 1
        if not Ass[t]:
            continue
        if Ass[t][0] == i + 1:
            Q.add(i)
            Q.add(t)
    for i in Q:
        Ass[i].popleft()

if any(Ass):
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque

n = int(input())
match = [deque([int(i)-1 for i in input().split()]) for _ in range(n)]
q = deque(range(n)) 
wait = [-1] * n 
finish_day = [0] * n 
match_count = 0 

while q:
    x = q.popleft()
    y = match[x].popleft()
    if wait[y] != x: 
        wait[x] = y
    else:
        match_count += 1
        match_day = max(finish_day[x], finish_day[y]) + 1
        finish_day[x] = finish_day[y] = match_day
        wait[x], wait[y] = -1, -1
        if match[x]: q.append(x)
        if match[y]: q.append(y)

if match_count != (n*(n-1)) /2:
    print(-1)
else:
    print(max(finish_day))

Solution (Python):
from collections import deque
N = int(input())

def trans(x):
    return int(x)-1

A = deque()
for _ in range(N):
    A.append(deque(map(trans,input().split())))

Q = set()

def check(i):
    if len(A[i]) == 0:
        return
    j = A[i][0]
    if len(A[j]) == 0:
        return
    if A[j][0] == i:
        if i > j:
            i, j = j, i
        Q.add((i, j))

for i in range(N):
    check(i)

ans = 0
while len(Q) > 0:
    ans += 1
    Q2 = Q.copy()
    Q = set()
    for q in Q2:
        A[q[0]].popleft()
        A[q[1]].popleft()
    for q in Q2:
        check(q[0])
        check(q[1])

for i in range(N):
    if len(A[i]) > 0:
        print(-1)
        exit()

print(ans)

Solution (Python):
from collections import defaultdict
n = int(input())
a = [[]]
for _ in range(n):
    tmp = [int(x) for x in input().split()]
    a.append(tmp[::-1])

p = [i for i in range(1, n+1)]
c = defaultdict(int)
done = 0
for d in range(1, n*(n-1)//2+1):
    np = []
    for pp in p:
        if len(a[pp]) == 0:
            continue
        x = a[pp].pop()
        l = min(x, pp)
        r = max(x, pp)
        c[l, r] += 1
        if c[l, r] == 2:
            np.append(l)
            np.append(r)
            done += 1
    if done == (n*(n-1)//2):
        print(d)
        exit()
    if len(np) == 0:
        print(-1)
        exit()
    p = np

Solution (Python):
from collections import deque

N = int(input())
ad = [[] for _ in range(N*N)]
num = [0] * (N*N)

for i in range(N):
    a = [int(e)-1 for e in input().split()]
    for k in range(N-2):
        j = a[k]
        nj = a[k+1]
        v = N*max(i,j) + min(i,j)
        nv = N*max(i,nj) + min(i,nj)
        ad[v].append(nv)
        num[nv] += 1

S = deque()
L = []

for v in range(N*N):
    if num[v] == 0:
        S.append((v,1))

while S:
    v, d = S.popleft()
    L.append(d)
    for nv in ad[v]:
        num[nv] -= 1
        if num[nv] == 0:
            S.append((nv, d+1))

if len(L) != N*N:
    print(-1)
    exit()

ans = max(L)
print(ans)

Solution (Python):
import sys

input = sys.stdin.readline
sys.setrecursionlimit(100000)
from collections import deque


def getN():
    return int(input())


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


import math

n = getN()

match = [0 for i in range((n * (n - 1)) // 2)]
child = [[] for i in range((n * (n - 1)) // 2)]
iriji = [0 for i in range((n * (n - 1)) // 2)]


def toposo(n, iriji, child):
    order = [0 for i in range((n*(n+1))//2)]
    q = deque([])
    for i, iri in enumerate(iriji):
        if iri == 0:
            q.append(i)
            order[i] = 1
    while(q):
        start = q.popleft()
        target = child[start]
        for tgt in target:
            iriji[tgt] -= 1
            if iriji[tgt] == 0:
                q.append(tgt)
                order[tgt] = order[start] + 1

    if sum(iriji) != 0:
        return -1

    else:
        return max(order)


for idd in range(n):
    nums = getList()
    i = idd + 1
    for j, k in zip(nums, nums[1:]):
        ii, j = min(i, j), max(i, j)
        iii, k = min(i, k), max(i, k)
        idx1 = ((j - 1) * (j - 2)) // 2 + (ii - 1)
        idx2 = ((k - 1) * (k - 2)) // 2 + (iii - 1)
        iriji[idx2] += 1
        child[idx1].append(idx2)
        
        

















print(toposo(n, iriji, child))

Solution (Python):
import sys
input = sys.stdin.readline
n = int(input())
a = [[i-1 for i in map(int,input().split())][::-1] for j in range(n)]
def check(i):
  if a[i] == []:
    return
  elif a[a[i][-1]][-1] == i:
    q.add((min(a[i][-1],i),max(a[i][-1],i)))
q = set()
for i in range(n):
  check(i)
d = 0
while q:
  d += 1
  pq = set()
  pq,q = q,pq
  for i in pq:
    del a[i[0]][-1],a[i[1]][-1]
    check(i[0])
    check(i[1])
for i in a:
  if i != []:
    print(-1)
    exit()
print(d)

Solution (Python):
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
from collections import deque

import queue

def get_ind(pre_tuple, num):
    a, b = pre_tuple
    ans = (a - 1) * num + b
    return ans



def main():
    num = int(input())
    data = [list(map(int, input().split())) for i in range(num)]

    graph_data = [set() for i in range(num * num)]
    parent_node = [0 for i in range(num * num)]

    for i in range(num):
        now_node = i + 1
        pre_tuple = (0, 0)
        for j in range(num - 1):
            next_node = data[i][j]
            now_tuple = (min(now_node, next_node), max(now_node, next_node))
            if j == 0:
                pass
                
            else:
                index = get_ind(pre_tuple, num)
                
                graph_data[index].add(now_tuple)
                index2 = get_ind(now_tuple, num)
                parent_node[index2] += 1
            pre_tuple = now_tuple

    q = deque([])
    count_node, ans = 0, 0

    for i in range(1, num + 1):
        for j in range(i + 1, num + 1):
            node = (i, j)
            index = get_ind(node, num)
            if parent_node[index] == 0:
                q.append((node, 1))
                count_node += 1

    ans = 0
    while len(q) > 0:
        now_node, length = q.popleft()
        ans = max(ans, length)
        index = get_ind(now_node, num)
        for next_node in graph_data[index]:
            index2 = get_ind(next_node, num)
            parent_node[index2] -= 1
            if parent_node[index2] == 0:
                q.append((next_node, length + 1))
                count_node += 1

    if count_node < (num * (num - 1)) // 2:
        print(-1)
    else:
        print(ans)







if __name__ == '__main__':
    main()

Solution (Python):
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
from collections import deque

import queue

def get_ind(pre_tuple, num):
    a, b = pre_tuple
    ans = (a - 1) * num + b
    return ans



def main():
    num = int(input())
    data = [list(map(int, input().split())) for i in range(num)]

    graph_data = [set() for i in range(num * num)]
    parent_node = [0 for i in range(num * num)]

    for i in range(num):
        now_node = i + 1
        pre_tuple = (0, 0)
        for j in range(num - 1):
            next_node = data[i][j]
            now_tuple = (min(now_node, next_node), max(now_node, next_node))
            if j == 0:
                pass
                
            else:
                index = get_ind(pre_tuple, num)
                
                graph_data[index].add(now_tuple)
                index2 = get_ind(now_tuple, num)
                parent_node[index2] += 1
            pre_tuple = now_tuple

    q = deque([])
    count_node, ans = 0, 0

    for i in range(1, num + 1):
        for j in range(i + 1, num + 1):
            node = (i, j)
            index = get_ind(node, num)
            if parent_node[index] == 0:
                q.append((node, 1))
                count_node += 1

    while len(q) > 0:
        now_node, length = q.popleft()
        index = get_ind(now_node, num)
        for next_node in graph_data[index]:
            index2 = get_ind(next_node, num)
            parent_node[index2] -= 1
            if parent_node[index2] == 0:
                q.append((next_node, length + 1))
                count_node += 1

    if count_node < (num * (num - 1)) // 2:
        print(-1)
    else:
        print(length)







if __name__ == '__main__':
    main()