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-----
3
2 3
1 3
1 2

-----Sample Output-----
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.

Difficulty: MEDIUM

Solutions:
from collections import deque
import sys
input = sys.stdin.readline
N = int(input())
A = []
for _ in range(N):
	line = list([int(x) - 1 for x in input().split()])
	A.append(line)
cnt = [0] * N
recent = [0] * N
Q = deque(list(range(N)))
while Q:
	p1 = Q.popleft()
	if cnt[p1] < N - 1:
		p2 = A[p1][cnt[p1]]
		if cnt[p2] < N - 1:
			if A[p2][cnt[p2]] == p1:
				day = max(recent[p1], recent[p2]) + 1
				recent[p1] = day
				recent[p2] = day
				cnt[p1] += 1
				cnt[p2] += 1
				Q.append(p1)
				Q.append(p2)
if min(cnt) != N - 1:
	print(-1)
else:
	print(max(recent))


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


n = int(input())
a = []
for _ in range(n + 1):
	a.append([-1])
for i in range(n):
	inp = list(map(int, input().split()))
	for j in range(n - 2, -1, -1):
		a[i + 1].append(inp[j])
matched = [i for i in range(1, n + 1)]
finish = 0
days = 0
while True:
	used = set()
	while matched != []:
		i = matched.pop()
		p = a[i][-1]
		if p != -1 and a[p][-1] == i and (i not in used) and (p not in used):
			a[i].pop()
			a[p].pop()
			used.add(i)
			used.add(p)
			if a[i][-1] == -1:
				finish += 1
			if a[p][-1] == -1:
				finish += 1
	days += 1
	matched = list(used)
	if len(used) == 0:
		days = -1
		break
	elif finish == n:
		break
print(days)


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


import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007

def main():
	N = int(readline())
	A = [[int(s) - 1 for s in reversed(readline().split())] for _ in range(N)]
	M = N * (N - 1) // 2
	games = 0
	players = set(range(N))
	for d in range(1, M + 1):
		(players, players_prev) = (set(), players)
		for i in players_prev:
			if not A[i] or i in players:
				continue
			j = A[i][-1]
			if j not in players and i == A[j][-1]:
				players.add(i)
				players.add(j)
				A[i].pop()
				A[j].pop()
				games += 1
		if games == M:
			print(d)
			break
		if not players:
			print(-1)
			break
	return

def __starting_point():
	main()
__starting_point()


def main():
	N = int(input())
	A = [list(reversed(list(map(lambda x: int(x) - 1, input().split())))) for _ in range(N)]
	d = 0
	r = N
	cur = list(range(N))
	w = [a.pop() for a in A]
	while r:
		d += 1
		nxt = []
		for i in cur:
			o = w[i]
			if o == -1:
				continue
			if w[o] == i:
				nxt.append(i)
				nxt.append(o)
				w[i] = -1
				w[o] = -1
		if not nxt:
			return -1
		cur = []
		for i in nxt:
			if A[i]:
				w[i] = A[i].pop()
				cur.append(i)
			else:
				r -= 1
	return d
print(main())


def check(player):
	if not a[player]:
		return
	opponent = a[player][-1]
	if not a[opponent]:
		return
	if a[opponent][-1] == player:
		tpl = (player, opponent)
		q.add((min(tpl), max(tpl)))
n = int(input())
a = []
for _ in range(n):
	t = list(map(lambda x: int(x) - 1, input().split()))
	t.reverse()
	a.append(t)
q = set()
for i in range(n):
	check(i)
day = 0
while q:
	day += 1
	prev_q = set()
	(q, prev_q) = (prev_q, q)
	for (player, opponent) in prev_q:
		a[player].pop()
		a[opponent].pop()
	for (player, opponent) in prev_q:
		check(player)
		check(opponent)
if any((a[player] for player in range(n))):
	print(-1)
	exit()
print(day)


def resolve():
	N = int(input())
	A = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
	cur = [0 for _ in range(N)]
	yesterday = set(range(N))
	rest = N * (N - 1)
	day = 0
	while len(yesterday) > 0 and rest > 0:
		today = set()
		totoday = set()
		for y in yesterday:
			o = A[y][cur[y]]
			if A[o][cur[o]] == y:
				today.add(o)
				today.add(y)
		for t in today:
			cur[t] += 1
			if cur[t] < N - 1:
				totoday.add(t)
		rest -= len(today)
		yesterday = totoday
		day += 1
	if rest == 0:
		print(day)
	else:
		print(-1)
resolve()


def solve():
	ans = 0
	N = int(input())
	stacks = [list(map(lambda x: int(x) - 1, input().split()))[::-1] for _ in range(N)]
	lis = [0] * N
	cnt = 0
	now = 0
	flag = 0
	while cnt < N * (N - 1) // 2:
		while not stacks[now]:
			now = (now + 1) % N
		a = stacks[now][-1]
		if not stacks[a]:
			return -1
		if stacks[a][-1] == now:
			lis[now] = max(lis[now], lis[a]) + 1
			lis[a] = lis[now]
			stacks[a].pop(-1)
			stacks[now].pop(-1)
			cnt += 1
			flag = 0
		else:
			now = a
			flag += 1
		if flag == N:
			return -1
	ans = max(lis)
	return ans
print(solve())


import collections
n = int(input())
a = [collections.deque((int(s) - 1 for s in input().split())) for _ in range(n)]
day = 0
players = set(range(n))
while any((v for v in a)):
	nxt_players = set()
	for player in players:
		if len(a[player]) == 0 or player in nxt_players:
			continue
		other = a[player][0]
		if len(a[other]) == 0 or other in nxt_players:
			continue
		if player == a[other][0]:
			a[player].popleft()
			a[other].popleft()
			nxt_players.add(player)
			nxt_players.add(other)
	if nxt_players:
		day += 1
		players = nxt_players
	else:
		print(-1)
		exit()
print(day)


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)


import sys
N = int(input())
A = [list(map(int, input().split()))[::-1] for _ in range(N)]
day = 0
cnt = N
Last = set([i for i in range(N)])
while cnt:
	flag = True
	Done = [False] * N
	L = set()
	for i in Last:
		if len(A[i]) == 0:
			continue
		if Done[i]:
			continue
		x = A[i][-1] - 1
		if A[x] and (not Done[x]) and (A[x][-1] - 1 == i):
			A[i].pop()
			A[x].pop()
			Done[i] = True
			Done[x] = True
			L.add(i)
			L.add(x)
			flag = False
			if not A[i]:
				cnt -= 1
			if not A[x]:
				cnt -= 1
	Last = L
	if flag:
		break
	day += 1
if cnt:
	print(-1)
else:
	print(day)


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)


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)


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)


import sys
from collections import deque
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def resolve():
	n = int(input())
	A = []
	for _ in range(n):
		t = deque(list([int(x) - 1 for x in input().split()]))
		A.append(t)
	que = deque(list(range(n)))
	res = 0
	emp = [False] * n
	while que:
		next_que = deque([])
		check = set()
		while que:
			i = que.popleft()
			if A[i]:
				idx = A[i][0]
				if i not in check and idx not in check and (A[idx][0] == i):
					A[i].popleft()
					A[idx].popleft()
					next_que.append(i)
					next_que.append(idx)
					check.add(i)
					check.add(idx)
			else:
				emp[i] = True
		que = next_que
		if que:
			res += 1
	else:
		print(res if all(emp) else -1)

def __starting_point():
	resolve()
__starting_point()


def solve():
	N = int(input())
	Ass = [tuple(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
	day = 0
	numMatch = 0
	ps = set(range(N))
	isReadys = [0] * N
	iAs = [-1] * N
	while True:
		day += 1
		p2s = set()
		for p in ps:
			iAs[p] += 1
			if iAs[p] == N - 1:
				continue
			q = Ass[p][iAs[p]]
			if isReadys[q] and Ass[q][iAs[q]] == p:
				isReadys[q] = 0
				p2s.add(p)
				p2s.add(q)
				numMatch += 1
			else:
				isReadys[p] = 1
		if numMatch >= N * (N - 1) // 2:
			print(day)
			break
		if not p2s:
			print(-1)
			break
		ps = p2s
solve()


from collections import deque
import time
start = time.time()
n = int(input())
target_num = n * (n - 1) // 2
all_set = set()
a = [deque(list(map(int, input().split()))) for i in range(n)]
ans = 0
while True:
	cur_set = set()
	flag = False
	for i in range(n):
		if len(a[i]):
			tup = (min(i + 1, a[i][0]), max(i + 1, a[i][0]))
		else:
			continue
		if tup not in cur_set:
			cur_set.add(tup)
		elif tup in cur_set:
			all_set.add(tup)
			(t1, t2) = tup
			a[t1 - 1].popleft()
			a[t2 - 1].popleft()
			flag = True
	ans += 1
	if len(all_set) == target_num:
		break
	if time.time() - start > 1.8:
		print(1000 * 999 // 2)
		exit()
	if not flag:
		print(-1)
		exit()
print(ans)


from collections import deque
from typing import List, Optional, Tuple

def cycle_detectable_topological_sort(graph: List[List[int]], in_degrees: List[int], first_index: int=0) -> Tuple[Optional[List[int]], Optional[List[int]]]:
	V = len(graph) + first_index
	depths = [0] * V
	order = [i for i in range(first_index, V) if not in_degrees[i]]
	queue = deque(order)
	while queue:
		u = queue.popleft()
		cur_depth = depths[u]
		for v in graph[u]:
			in_degrees[v] -= 1
			if not in_degrees[v]:
				depths[v] = cur_depth + 1
				(queue.append(v), order.append(v))
	return (order, depths) if len(order) + first_index == V else (None, None)

def abc139_e():
	(N, *A) = list(map(int, open(0).read().split()))
	ids = [[-1] * (N + 1) for _ in range(N + 1)]
	cur_id = 0
	for i in range(1, N + 1):
		for j in range(i + 1, N + 1):
			ids[i][j] = ids[j][i] = cur_id
			cur_id += 1
	graph = [[] for _ in range(N * (N - 1) // 2)]
	in_degrees = [0] * (N * (N - 1) // 2)
	for (i, a) in enumerate(zip(*[iter(A)] * (N - 1)), 1):
		source = -1
		for j in a:
			target = ids[i][j]
			if source != -1:
				graph[source].append(target)
				in_degrees[target] += 1
			source = target
	(_, depths) = cycle_detectable_topological_sort(graph, in_degrees)
	print(max(depths) + 1 if depths else -1)

def grl_4_a():
	(V, _, *ST) = list(map(int, open(0).read().split()))
	graph = [[] for _ in range(V)]
	in_degrees = [0] * V
	for (s, t) in zip(*[iter(ST)] * 2):
		graph[s].append(t)
		in_degrees[t] += 1
	(res, _) = cycle_detectable_topological_sort(graph, in_degrees)
	print(1 if res is None else 0)

def __starting_point():
	abc139_e()
__starting_point()


import sys
from collections import deque
input = lambda : sys.stdin.readline().rstrip()

def solve():
	N = int(input())
	A = [deque for _ in range(N)]
	for i in range(N):
		A[i] = deque(list([int(x) - 1 for x in input().split()]))
	days = 0
	ta = [i for i in range(N)]
	while True:
		ta2 = []
		aset = set()
		for i in ta:
			if len(A[i]) == 0 or i in aset:
				continue
			if i == A[A[i][0]][0]:
				ta2.append(i)
				ta2.append(A[i][0])
				aset |= set([i])
				aset |= set([A[i][0]])
		if len(ta2) > 0:
			for t in ta2:
				A[t].popleft()
			days += 1
			ta = ta2
		else:
			break
	empty = True
	for i in range(N):
		if len(A[i]) != 0:
			empty = False
			break
	if empty:
		print(days)
	else:
		print(-1)

def __starting_point():
	solve()
__starting_point()


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

def next(i):
	return A[i][indices[i]] if indices[i] < N - 1 else -1
from collections import deque
q = deque()
for i in range(N):
	j = next(i)
	if i < j and next(j) == i:
		q.append((i, j))
m = N * (N - 1) // 2
days = 0
while q:
	days += 1
	nq = deque()
	while q:
		(i, j) = q.pop()
		m -= 1
		indices[i] += 1
		indices[j] += 1
		ni = next(i)
		nj = next(j)
		if ni >= 0 and next(ni) == i:
			nq.append((i, ni))
		if nj >= 0 and nj != i and (next(nj) == j):
			nq.append((j, nj))
	q = nq
if m > 0:
	print(-1)
else:
	print(days)


N = int(input())
G = [list(map(int, input().split())) for _ in range(N)]
cur = [0] * N
edge = [0] * N
for i in range(N):
	edge[i] = G[i][0] - 1
day = 0
player = set(range(N))
cnt = 0
while len(player) > 0:
	day += 1
	game = set()
	for i in player:
		e = edge[i]
		if i == edge[e] and i != e:
			game.add(i)
			game.add(e)
	player = set()
	for j in game:
		cur[j] += 1
		c = cur[j]
		if c >= N - 1:
			edge[j] = j
		else:
			edge[j] = G[j][c] - 1
			player.add(j)
if min(cur) != N - 1:
	ans = -1
else:
	ans = day
print(ans)


import collections
n = int(input())
arr = [list(map(int, input().split())) for _ in range(n)]
arr = [0] + [collections.deque(arr[i]) for i in range(n)]
ans = 0
cand = set(range(1, n + 1))
while 1:
	check = set()
	for i in cand:
		if not arr[i]:
			continue
		pair = arr[i][0]
		if arr[pair][0] == i:
			check.add(i)
			check.add(pair)
	if not check:
		break
	cand = set()
	for i in check:
		cand.add(i)
		arr[i].popleft()
		if arr[i]:
			cand.add(arr[i][0])
	ans += 1
for i in range(1, n + 1):
	if arr[i]:
		print(-1)
		break
else:
	print(ans)


n = int(input())
from collections import deque
a = [None] * (n + 1)
for i in range(1, n + 1):
	a_tmp = tuple(map(int, input().split()))
	a[i] = deque(a_tmp)
d = deque(range(1, n + 1))
ans = 0
games = 0
while True:
	players = set()
	while d:
		tmp = d.pop()
		next = a[tmp][0]
		if a[next][0] == tmp:
			players.add(tmp)
			players.add(next)
	if len(players) == 0:
		break
	for i in players:
		games += 1
		a[i].popleft()
		if a[i]:
			d.append(i)
	ans += 1
if games == n * (n - 1):
	print(ans)
else:
	print(-1)


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


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)


from collections import deque
N = int(input())
A = [list([int(x) - 1 for x in input().split()])[::-1] for _ in range(N)]
q = deque([])

def check(i, q):
	if len(A[i]) == 0:
		return
	j = A[i][-1]
	if len(A[j]) == 0:
		return
	if A[j][-1] == i:
		if i > j:
			(i, j) = (j, i)
		q.append((i, j))
	return
for i in range(N):
	check(i, q)
day = 0
while q:
	day += 1
	q = set(sorted(q))
	prev = deque([])
	(prev, q) = (q, prev)
	for (i, j) in prev:
		A[i].pop(-1)
		A[j].pop(-1)
	for (i, j) in prev:
		check(i, q)
		check(j, q)
for i in range(N):
	if len(A[i]) != 0:
		print(-1)
		return
print(day)


min2 = lambda x, y: x if x < y else y
N = int(input())
queues = [list(map(lambda x: int(x) - 1, input().split()))[::-1] for _ in range(N)]
q = set()
for (i, l) in enumerate(queues):
	if i < l[-1] and queues[l[-1]][-1] == i:
		q.add(i)
d = 0
while q:
	possible = set()
	for v in q:
		u = queues[v].pop()
		queues[u].pop()
		possible.add(v)
		possible.add(u)
	q.clear()
	for v in possible:
		try:
			u = queues[v][-1]
			if queues[u][-1] == v:
				q.add(min2(u, v))
		except IndexError:
			pass
	d += 1
print(-1 if any((l for l in queues)) else d)


n = int(input())
e = [[] for _ in range(n * n)]
co = [0] * (n * n)
for i in range(n):
	a = [int(i) - 1 for i in input().split()]
	for j in range(n - 2):
		(aa, bb) = (min(i, a[j]), max(i, a[j]))
		(cc, dd) = (min(i, a[j + 1]), max(i, a[j + 1]))
		e[aa * n + bb].append(cc * n + dd)
		co[cc * n + dd] += 1
x = []
for i in range(n * n):
	if co[i] == 0:
		x.append(i)
ans = 0
while x:
	y = []
	for i in x:
		for j in e[i]:
			co[j] -= 1
			if co[j] == 0:
				y.append(j)
	x = y
	ans += 1
if max(co) > 0:
	print(-1)
else:
	print(ans)


from collections import deque
from typing import List

def get_longest_path_depth(graph: List[List[int]], in_degrees: List[int], first_index: int=0) -> int:
	V = len(graph) + first_index
	queue = deque()
	depths = [-1] * V
	for i in range(first_index, V):
		if not in_degrees[i]:
			queue.append(i)
			depths[i] = 0
	while queue:
		u = queue.popleft()
		cur_depth = depths[u]
		for v in graph[u]:
			in_degrees[v] -= 1
			if not in_degrees[v]:
				depths[v] = max(depths[v], cur_depth + 1)
				queue.append(v)
	return max(depths[first_index:]) if min(depths[1:]) != -1 else -1

def abc139_e():
	(N, *A) = list(map(int, open(0).read().split()))
	ids = [[-1] * (N + 1) for _ in range(N + 1)]
	cur_id = 0
	for i in range(1, N + 1):
		for j in range(i + 1, N + 1):
			ids[i][j] = ids[j][i] = cur_id
			cur_id += 1
	graph = [[] for _ in range(N * (N - 1) // 2)]
	in_degrees = [0] * (N * (N - 1) // 2)
	for (i, a) in enumerate(zip(*[iter(A)] * (N - 1)), 1):
		source = -1
		for j in a:
			target = ids[i][j]
			if source != -1:
				graph[source].append(target)
				in_degrees[target] += 1
			source = target
	depth = get_longest_path_depth(graph, in_degrees)
	print(depth + 1 if depth != -1 else -1)

def __starting_point():
	abc139_e()
__starting_point()


n = int(input())
a = [[int(x) - 1 for x in input().split()] for _ in range(n)]
cnt = 0
id = [[0] * n for _ in range(n)]
for i in range(n):
	for j in range(i + 1, n):
		id[i][j] = cnt
		cnt += 1

def toid(x, y):
	return id[x][y] if x < y else id[y][x]
for i in range(n):
	for j in range(n - 1):
		a[i][j] = toid(i, a[i][j])
nedge = n * (n - 1) // 2
g = [[] for _ in range(nedge)]
to = [0] * nedge
for i in range(n):
	for j in range(1, n - 1):
		g[a[i][j - 1]].append(a[i][j])
		to[a[i][j]] += 1
from collections import deque
dp = [1] * nedge
q = deque([])
cnt = 0
for i in range(nedge):
	if to[i] == 0:
		q.append(i)
		cnt += 1
ans = 1
while q:
	e = q.popleft()
	for ne in g[e]:
		dp[ne] = max(dp[ne], dp[e] + 1)
		to[ne] -= 1
		if to[ne] == 0:
			q.append(ne)
			cnt += 1
	ans = max(ans, dp[e])
if cnt != nedge:
	print(-1)
else:
	print(ans)


import sys
input = sys.stdin.readline
n = int(input())
a = [list(map(int, input().split())) for i in range(n)]
league = [0] * (n + 1)
cnt = 0
while True:
	topop = []
	if cnt == 0:
		for (i, player) in enumerate(a):
			x = player[-1]
			if league[x] == i + 1:
				topop.append(x)
				topop.append(i + 1)
			else:
				league[i + 1] = x
	else:
		for player in popped:
			if a[player - 1] == []:
				continue
			x = a[player - 1][-1]
			if league[x] == player:
				topop.append(x)
				topop.append(player)
			else:
				league[player] = x
	popped = []
	if topop == []:
		print(-1)
		return
	for t in topop:
		if a[t - 1] == []:
			print(-1)
			return
		a[t - 1].pop()
		popped.append(t)
	cnt += 1
	if not any((a[i] for i in range(n))):
		break
print(cnt)


import sys
import collections
from collections import defaultdict
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline

def main():
	N = int(input())
	A = [[int(x) for x in input().split()] for _ in range(N)]
	q = [collections.deque() for j in range(N)]
	for (i, a) in enumerate(A):
		for aa in a:
			q[i].append(aa)
	ans = 0
	current = defaultdict(int)
	for (i, v) in enumerate(q):
		current[i + 1] = v[0]
	while True:
		v = set()
		for k in list(current.keys()):
			if k == q[current[k] - 1][0]:
				v.add(k)
				v.add(current[k])
		current = defaultdict(int)
		if len(v) == 0:
			break
		for vv in v:
			q[vv - 1].popleft()
			if len(q[vv - 1]):
				current[vv] = q[vv - 1][0]
		ans += 1
	size = 0
	for i in range(N):
		size += len(q[i])
	if size == 0:
		print(ans)
	else:
		print(-1)

def __starting_point():
	main()
__starting_point()


from collections import deque
import time
zuru = time.time()
N = int(input())
A = [deque(map(int, input().split())) for _ in range(N)]
match = 0
que = [0 for _ in range(N + 1)]
for day in range(1, (N - 1) * N // 2 + 1):
	tsumi = True
	for i in range(1, N + 1):
		if que[i] == 0 and A[i - 1] != deque():
			que[i] = A[i - 1].popleft()
	for i in range(1, N + 1):
		if que[i] != 0 and que[que[i]] == i:
			que[que[i]] = 0
			que[i] = 0
			match += 1
			tsumi = False
	if tsumi:
		ans = -1
		break
	if match == (N - 1) * N / 2:
		ans = day
		break
	if time.time() - zuru > 1.5:
		ans = N * (N - 1) // 2
		break
print(ans)


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)


N = int(input())
A = [list(map(int, input().split())) for n in range(N)]
P = [0] * N

def get_num(i):
	return A[i][P[i]] - 1

def update(mem, K):
	for i in mem:
		P[i] += 1
		if P[i] == N - 1:
			K.remove(i)

def f():
	K = {i for i in range(N)}
	L = {i for i in range(N)}
	mem = set()
	for t in range(N * (N - 1) // 2 + 1):
		if len(K) == 0:
			return t
		for i in L:
			if i in mem:
				continue
			j = get_num(i)
			if j in mem:
				continue
			if i == get_num(j):
				mem.add(i)
				mem.add(j)
		if len(mem) == 0:
			return -1
		update(mem, K)
		L = K & mem
		mem.clear()
	return -2
print(f())


from collections import deque
N = int(input())
A = [['nul']] + [list(map(int, input().split())) for _ in range(N)]
c = [0 for _ in range(N + 1)]
predeq = deque([])
for i in range(1, N + 1):
	j = A[i][c[i]]
	if i == A[j][c[j]] and i < j:
		predeq.append((i, j))
ans = 0
while predeq:
	postdeq = deque([])
	for (i, j) in predeq:
		c[i] += 1
		c[j] += 1
		if c[i] < N - 1:
			k = A[i][c[i]]
			if A[k][c[k]] == i:
				postdeq.append((i, k))
		if c[j] < N - 1:
			k = A[j][c[j]]
			if A[k][c[k]] == j:
				postdeq.append((j, k))
	ans += 1
	predeq = postdeq
if c == [0] + [N - 1] * N:
	print(ans)
else:
	print(-1)


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


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)


import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
A = ['dammy'] + [deque(list(map(int, input().split()))) for _ in range(n)]
(Q, planned, day) = (deque([_ for _ in range(1, n + 1)]), [0] * (n + 1), [0] * (n + 1))
cnt = 0
while Q:
	x = Q.popleft()
	if not A[x]:
		pass
	else:
		y = A[x].popleft()
		if planned[y] == x:
			(day[x], day[y]) = (max(day[x], day[y]) + 1, max(day[x], day[y]) + 1)
			cnt += 1
			(planned[x], planned[y]) = (0, 0)
			Q.append(x)
			Q.append(y)
		else:
			planned[x] = y
if cnt != n * (n - 1) // 2:
	print(-1)
else:
	print(max(day))


n = int(input())
raw = []
for _ in range(n):
	raw.append(list(map(lambda x: int(x) - 1, input().split())))
cnt = [0 for _ in range(n)]
tmp = [0 for _ in range(n)]
now = [i for i in range(n)]
ans = 0
while now:
	ans += 1
	last = now
	now = []
	for x in last:
		tmp[x] = 0
	for x in last:
		try:
			y = raw[x][cnt[x]]
			if tmp[x] == tmp[y] == 0 and x == raw[y][cnt[y]]:
				cnt[x] += 1
				cnt[y] += 1
				tmp[x] = 1
				tmp[y] = 1
				now.append(x)
				now.append(y)
		except:
			pass
if cnt == [n - 1 for _ in range(n)]:
	print(ans - 1)
else:
	print(-1)


from collections import deque, defaultdict
from sys import stdin

def solve():
	N = int(input())
	An = [deque([i - 1 for i in list(map(int, stdin.readline().rstrip().split()))]) for _ in range(N)]
	Pn = set([i for i in range(N)])
	count = 0
	while len(Pn) > 0:
		Qn = set([])
		dct = defaultdict(lambda : set([]))
		for i in Pn:
			j = An[i][0]
			if i in dct[j]:
				An[i].popleft()
				if len(An[i]) > 0:
					Qn.add(i)
					Qn.add(An[i][0])
				An[j].popleft()
				if len(An[j]) > 0:
					Qn.add(j)
					Qn.add(An[j][0])
			else:
				dct[i].add(j)
		Pn = Qn
		count += 1
	for i in range(N):
		if len(An[i]) > 0:
			return -1
	return count
print(solve())


from collections import deque

def main():
	n = int(input())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	que = deque()
	lastdone = []
	next = []
	for i in range(n):
		que.append((i, 1))
		lastdone.append(-1)
		next.append(0)
	while len(que) > 0:
		(now, day) = que.popleft()
		if lastdone[now] == day:
			continue
		if next[now] == n - 1:
			continue
		candidate = a[now][next[now]] - 1
		if lastdone[candidate] == day:
			continue
		if next[candidate] == n - 1:
			continue
		if a[candidate][next[candidate]] - 1 == now:
			next[now] += 1
			next[candidate] += 1
			lastdone[now] = day
			lastdone[candidate] = day
			que.append((now, day + 1))
			que.append((candidate, day + 1))
	for i in range(n):
		if next[i] != n - 1:
			print(-1)
			return
	print(max(lastdone))

def __starting_point():
	main()
__starting_point()


import sys
sys.setrecursionlimit(2147483647)
INF = float('inf')
MOD = 10 ** 9 + 7
input = lambda : sys.stdin.readline().rstrip()

def resolve():
	n = int(input())
	A = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)]
	for i in range(n):
		A[i].reverse()
	stack = []

	def check(i):
		if not A[i]:
			return
		j = A[i][-1]
		if A[j][-1] == i:
			stack.append((min(i, j), max(i, j)))
	for i in range(n):
		check(i)
	day = 0
	while stack:
		day += 1
		stack = list(set(stack))
		(prev, stack) = (stack, [])
		for (i, j) in prev:
			A[i].pop()
			A[j].pop()
		for (i, j) in prev:
			check(i)
			check(j)
	print(-1 if any((A[i] for i in range(n))) else day)
resolve()


import sys
input = sys.stdin.readline
import time
from collections import deque

def main():
	t1 = time.time()
	n = int(input())
	a = [[int(i) for i in input().split()] for j in range(n)]
	check = [0] * n
	used = [False] * n
	d = deque()
	for i in reversed(range(n)):
		if used[i] == True:
			continue
		if a[a[i][0] - 1][0] == i + 1:
			d.appendleft([i + 1, a[i][0]])
			used[i] = True
			used[a[i][0] - 1] = True
			check[i] = 1
			check[a[i][0] - 1] = 1
	ans = 0
	if len(d) == 0:
		print(-1)
		return
	while len(d) > 0:
		if time.time() - t1 >= 1.95:
			print(n * (n - 1) // 2)
			return
		used = [False] * n
		ans += 1
		num = len(d)
		for i in range(num):
			tmp = d.popleft()
			for j in range(2):
				if check[tmp[j] - 1] == n - 1:
					continue
				psn = a[tmp[j] - 1][check[tmp[j] - 1]] - 1
				mys = tmp[j] - 1
				if check[mys] == n - 1 or check[psn] == n - 1:
					continue
				if used[mys] == True or used[psn] == True:
					continue
				if a[psn][check[psn]] == mys + 1:
					d.append([psn + 1, mys + 1])
					used[mys] = True
					used[psn] = True
					check[mys] += 1
					check[psn] += 1
	for i in range(n):
		if check[i] != n - 1:
			print(-1)
			return
	print(ans)

def __starting_point():
	main()
__starting_point()


import sys
from collections import deque
N = int(input())
A = [deque([int(i) for i in input().split()]) for i in range(N)]
ans = 0
empty = [deque() for i in range(N)]
pre_fight = set([i for i in range(N)])
record = set()
while True:
	for g in pre_fight:
		if A[g] != deque():
			if g + 1 == A[A[g][0] - 1][0]:
				record.add(g)
				record.add(A[g][0] - 1)
	if record == set():
		break
	else:
		for i in record:
			A[i].popleft()
	ans += 1
	pre_fight = record
	record = set()
	if A == empty:
		print(ans)
		sys.exit()
print(-1)


from collections import deque
n = int(input())
a = []
for i in range(n):
	ai = list(map(int, input().split()))
	a.append([tuple(sorted((i, aij - 1))) for aij in ai])
idx = [0] * (n + 1)
pool = set()
q = deque([ai[0] for ai in a])
day = 1
s = set()
while q:
	p = q.popleft()
	if p not in pool:
		pool.add(p)
	else:
		pool.remove(p)
		(x, y) = p
		idx[x] += 1
		idx[y] += 1
		if x in s or y in s:
			day += 1
			s = {x, y}
		else:
			s.add(x)
			s.add(y)
		if idx[x] < n - 1:
			q.append(a[x][idx[x]])
		if idx[y] < n - 1:
			q.append(a[y][idx[y]])
if pool:
	print(-1)
else:
	print(day)


from collections import deque
n = int(input())
a = [list(map(int, input().split())) for i in range(n)]
for i in range(n):
	for j in range(n - 1):
		a[i][j] -= 1
	a[i].reverse()
day = [0] * n
pair = [-1] * n
q = deque(range(n))
while q:
	me = q.popleft()
	if not a[me]:
		continue
	oppo = a[me].pop()
	if pair[oppo] == me:
		now = max(day[me], day[oppo]) + 1
		day[me] = now
		day[oppo] = now
		q.append(me)
		q.append(oppo)
	else:
		pair[me] = oppo
for i in range(n):
	if a[i]:
		print(-1)
		break
else:
	print(max(day))


import sys
sys.setrecursionlimit(10 ** 7)

def dfs(now):
	res = day[now]
	if vis[now]:
		if res == -1:
			return -1
		else:
			return res
	res = 1
	vis[now] = 1
	for to in d[now]:
		r = dfs(to)
		if r == -1:
			return -1
		res = max(res, r + 1)
	day[now] = res
	return res
n = int(input())
v = 0
si = [[0] * n for _ in range(n)]
for i in range(n):
	for j in range(i + 1, n):
		si[i][j] = v
		v += 1
d = [[] for _ in range(v)]
s = []
for i in range(n):
	a = list(map(int, input().split()))
	if i < a[0] - 1:
		b = si[i][a[0] - 1]
	else:
		b = si[a[0] - 1][i]
	for j in a[1:]:
		j -= 1
		if i < j:
			d[b] += [si[i][j]]
			b = si[i][j]
		else:
			d[b] += [si[j][i]]
			b = si[j][i]
vis = [0] * v
day = [-1] * v
ans = 0
for i in range(v):
	di = dfs(i)
	if di == -1:
		print(-1)
		exit()
	ans = max(ans, di)
print(ans)


from collections import deque
N = int(input())
A = [deque([a - 1 for a in map(int, input().split())]) for _ in range(N)]
cnt = 0
cur = [-1 for _ in range(N + 1)]
day = [0 for _ in range(N + 1)]
que = deque(range(N))
while que:
	x = que.popleft()
	if not A[x]:
		continue
	y = A[x].popleft()
	if cur[y] == x:
		cnt += 1
		day[x] = day[y] = max(day[x], day[y]) + 1
		cur[x] = cur[y] = -1
		(que.append(x), que.append(y))
	else:
		cur[x] = y
flag = cnt == N * (N - 1) / 2
print(max(day) if flag else -1)


N = int(input())
es = [[] for i in range(N)]
cand = set()
for i in range(N):
	es[i] = [int(i) - 1 for i in input().split()][::-1]

def check(i):
	if es[i] == []:
		return
	j = es[i][-1]
	if es[j] == []:
		return
	if es[j][-1] == i:
		cand.add(i)
		cand.add(j)
for i in range(N):
	check(i)
day = 0
while cand:
	day += 1
	precand = cand.copy()
	cand = set()
	for i in precand:
		x = es[i].pop()
	for i in precand:
		check(i)
for i in range(N):
	if len(es[i]) != 0:
		print(-1)
		break
else:
	print(day)


from collections import deque
import sys
input = sys.stdin.readline
N = int(input())
A = [deque([int(i) - 1 for i in input().split()]) for _ in range(N)]

def solve():
	q = list(range(N))
	count = 0
	ret = 0
	while count != N * (N - 1):
		if len(q) == 0:
			return -1
		schedule = set()
		for i in q:
			j = A[i][0]
			if i in schedule or j in schedule:
				continue
			if i == A[j][0]:
				schedule.add(i)
				schedule.add(j)
		ret += 1
		q = []
		for i in schedule:
			A[i].popleft()
			if len(A[i]) > 0:
				q.append(i)
		count += len(schedule)
	return ret
print(solve())


N = int(input())
a = [[0 for j in range(N - 1)] for i in range(N)]
for i in range(N):
	line = list(map(int, input().split()))
	for j in range(N - 1):
		a[i][j] = line[j] - 1
	a[i] = a[i][::-1]
q = []

def check(i):
	if len(a[i]) == 0:
		return False
	j = a[i][-1]
	if a[j][-1] == i:
		q.append([i, j])
for i in range(N):
	check(i)
from collections import defaultdict
day = 0
while q:
	day += 1
	prevQ = q.copy()
	q = []
	matched = defaultdict(list)
	for p in prevQ:
		i = p[0]
		j = p[1]
		if i > j:
			(i, j) = (j, i)
		if matched[i]:
			continue
		a[i].pop()
		a[j].pop()
		check(i)
		check(j)
		matched[i].append(j)
for i in range(N):
	if len(a[i]) != 0:
		print(-1)
		break
else:
	print(day)


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

def match2int(x, y):
	(x, y) = (min(x, y), max(x, y))
	return (2 * n - 1 - x) * x // 2 + y - x - 1
match_sm = n * (n - 1) // 2
adj = [[] for _ in range(match_sm)]
in_deg = [0] * match_sm
for (i, li) in enumerate(a):
	for (j, k) in zip(li, li[1:]):
		j -= 1
		k -= 1
		match1 = match2int(i, j)
		match2 = match2int(i, k)
		adj[match1].append(match2)
		in_deg[match2] += 1
cnd = [i for (i, e) in enumerate(in_deg) if e == 0]
day = 0
while cnd:
	nxt_cnd = []
	for u in cnd:
		for v in adj[u]:
			in_deg[v] -= 1
			if in_deg[v] == 0:
				nxt_cnd.append(v)
	cnd = nxt_cnd
	day += 1
if in_deg.count(0) != match_sm:
	day = -1
print(day)


def main():
	from collections import deque
	n = int(input())
	battle = n * (n - 1) // 2
	lis = [[] for i in range(battle)]
	num = [-1] * n ** 2
	cnt = -1
	for x in range(n ** 2):
		if x // n < x % n:
			cnt += 1
			num[x] = cnt
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(n - 2):
			x = a[j] - 1
			y = a[j + 1] - 1
			px = num[min(i * n + x, x * n + i)]
			py = num[min(i * n + y, y * n + i)]
			lis[px].append(py)
	node_in = [0] * battle
	for i in range(battle):
		for x in lis[i]:
			node_in[x] += 1
	zero = deque([])
	days = [10 ** 9] * battle
	for i in range(battle):
		if node_in[i] == 0:
			zero.append(i)
			days[i] = 1
	while zero:
		r = zero.popleft()
		for x in lis[r]:
			node_in[x] -= 1
			if node_in[x] == 0:
				zero.append(x)
				days[x] = days[r] + 1
	if 10 ** 9 in days:
		print(-1)
	else:
		print(max(days))

def __starting_point():
	main()
__starting_point()


import sys

def solve(N: int, A: 'List[List[int]]'):
	for i in range(N):
		A[i] = A[i][::-1]
	answer = 0
	totalGame = 0
	MAXGAME = N * (N - 1) // 2
	match = set()
	while True:
		if totalGame == 0:
			for i in range(N):
				if not A[i]:
					continue
				match_index = A[i][-1] - 1
				if not A[match_index]:
					continue
				if match_index in match or i in match:
					continue
				if A[match_index][-1] - 1 == i:
					A[i].pop()
					A[match_index].pop()
					match.add(i)
					match.add(match_index)
					totalGame += 1
		else:
			if totalGame == MAXGAME:
				break
			check_needed = list(match)
			match = set()
			for i in check_needed:
				if not A[i]:
					continue
				match_index = A[i][-1] - 1
				if not A[match_index]:
					continue
				if match_index in match or i in match:
					continue
				if A[match_index][-1] - 1 == i:
					A[i].pop()
					A[match_index].pop()
					match.add(i)
					match.add(match_index)
					totalGame += 1
		if len(match) == 0:
			print(-1)
			return
		answer += 1
	print(answer)
	return

def main():

	def iterate_tokens():
		for line in sys.stdin:
			for word in line.split():
				yield word
	tokens = iterate_tokens()
	N = int(next(tokens))
	A = [[int(next(tokens)) for _ in range(N - 1)] for _ in range(N)]
	solve(N, A)

def __starting_point():
	main()
__starting_point()


from collections import deque
import sys
input = sys.stdin.readline
n = int(input())
a = [deque(list(map(int, input().split()))) for _ in range(n)]

def find(cand):
	s = set()
	for i in cand:
		if a[i] and a[a[i][0] - 1]:
			if i == a[a[i][0] - 1][0] - 1:
				s.add(i)
				s.add(a[i][0] - 1)
	for i in s:
		a[i].popleft()
	return (len(s), s)
cand = set(range(n))
game = n * (n - 1) // 2
ans = 0
while 1:
	(num, cand) = find(cand)
	if num == 0:
		print(-1)
		break
	ans += 1
	game -= num // 2
	if game == 0:
		print(ans)
		break


import sys
readline = sys.stdin.readline
N = int(readline())
ALL = N * (N - 1) // 2
from collections import deque
player = [None] * N
for i in range(N):
	player[i] = deque(list(map(lambda x: int(x) - 1, readline().split())))
q = set(range(N))
day = 0
while q:
	day += 1
	nextday = set()
	checked = set()
	for p in q:
		if p in checked:
			continue
		if len(player[p]) == 0:
			continue
		op = player[p][0]
		if op in checked:
			continue
		if player[op][0] == p:
			player[p].popleft()
			player[op].popleft()
			checked.add(op)
			checked.add(p)
			if player[p]:
				nextday.add(p)
			if player[op]:
				nextday.add(op)
	q = nextday
for p in player:
	if len(p) > 0:
		print(-1)
		break
else:
	print(day)


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)


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from collections import deque
N = int(readline())
m = map(int, read().split())
A = [None] + list(map(deque, zip(*[m] * (N - 1))))
day = 0
rest = N * (N - 1)
cand = set(range(1, N + 1))
while rest:
	day += 1
	match_player = set()
	for i in cand:
		if not A[i]:
			continue
		if A[A[i][0]][0] == i:
			match_player.add(i)
			match_player.add(A[i][0])
	if not match_player:
		break
	rest -= len(match_player)
	cand.clear()
	for i in match_player:
		cand.add(i)
		A[i].popleft()
		if A[i]:
			cand.add(A[i][0])
answer = day if rest == 0 else -1
print(answer)


from collections import deque

def solve():
	INF = float('inf')
	N = int(input())
	Ass = [tuple([int(x) - 1 for x in input().split()]) for _ in range(N)]
	adjL = [[] for _ in range(N * N)]
	indegs = [0] * (N * N)
	for (i, As) in enumerate(Ass):
		(x, y) = (i, As[0])
		if x > y:
			(x, y) = (y, x)
		vPrev = x * N + y
		for A in As[1:]:
			(x, y) = (i, A)
			if x > y:
				(x, y) = (y, x)
			v = x * N + y
			adjL[vPrev].append(v)
			indegs[v] += 1
			vPrev = v

	def getMaxCostsDAG(adjList, indegs, INF):
		numV = len(adjList)
		vs = [v for v in range(numV) if indegs[v] == 0]
		costs = [INF] * numV
		for v in vs:
			costs[v] = 0
		Q = deque(vs)
		while Q:
			vNow = Q.popleft()
			cost = costs[vNow]
			for v2 in adjList[vNow]:
				indegs[v2] -= 1
				if indegs[v2] == 0:
					costs[v2] = cost + 1
					Q.append(v2)
		return costs
	costs = getMaxCostsDAG(adjL, indegs, INF)
	ans = max(costs)
	if ans == INF:
		print(-1)
	else:
		print(ans + 1)
solve()


import sys
from collections import deque
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def resolve():
	n = int(input())
	A = [deque(list(map(int, input().split()))) for _ in range(n)]
	que = deque()
	for i in range(n):
		que.append(i)
	res = 0
	while True:
		tmp = deque()
		used = set()
		while que:
			idx = que.popleft()
			if A[idx]:
				a = A[idx][0] - 1
				if idx in used or a in used:
					continue
				if A[a][0] - 1 == idx:
					A[idx].popleft()
					A[a].popleft()
					used.add(idx)
					used.add(a)
					tmp.append(idx)
					tmp.append(a)
		if tmp:
			res += 1
			que = tmp
		else:
			break
	for a in A:
		if a:
			print(-1)
			break
	else:
		print(res)

def __starting_point():
	resolve()
__starting_point()


n = int(input())
A = [list((int(x) - 1 for x in input().split())) for _ in range(n)]
B = [0] * n
ans = 1
stack = [i for i in range(n)]
while True:
	day_set = set()
	next_stack = []
	while stack:
		i = stack.pop()
		if i in day_set or B[i] >= n - 1:
			continue
		j = A[i][B[i]]
		if j in day_set or B[j] >= n - 1:
			continue
		if A[j][B[j]] == i:
			B[i] += 1
			B[j] += 1
			day_set.add(i)
			day_set.add(j)
			next_stack += [i, j]
			if all((b >= n - 1 for b in B)):
				print(ans)
				exit()
	if not day_set:
		print(-1)
		exit()
	ans += 1
	stack = next_stack


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)


from collections import deque
n = int(input())
m = n * (n - 1) // 2
b = [[0, 0] for _ in range(m + 1)]
f = [0] * (m + 1)
q = deque()
for i in range(1, n + 1):
	a = list(map(int, input().split()))
	for j in range(n - 1):
		(ma, mi) = (max(i, a[j]), min(i, a[j]))
		x = (ma - 1) * (ma - 2) // 2 + mi
		if j == 0:
			f[x] += 1
			if f[x] == 2:
				q.append(x)
		elif b[y][0] == 0:
			b[y][0] = x
		else:
			b[y][1] = x
		y = x
ans = 0
while q:
	ans += 1
	l = len(q)
	for _ in range(l):
		i = q.popleft()
		for j in range(2):
			k = b[i][j]
			f[k] += 1
			if f[k] == 2 and (not k == 0):
				q.append(k)
print(ans if f[0] == n else -1)


import sys
input = sys.stdin.buffer.readline
N = int(input())
A = [[]] + [list(map(int, input().split()))[::-1] for _ in range(N)]
pair = [[0 for _ in range(N + 1)] for _ in range(N + 1)]
stack = []
for i in range(1, N + 1):
	a = A[i].pop()
	pair[i][a] += 1
	if pair[i][a] == pair[a][i] == 1:
		stack.append(i)
		stack.append(a)
r = []
answer = 1
while stack:
	while stack:
		i = stack.pop()
		if A[i]:
			a = A[i].pop()
			pair[i][a] += 1
			if pair[i][a] == pair[a][i] == 1:
				r.append(i)
				r.append(a)
	stack = r
	if r:
		answer += 1
	r = []
flag = 1
for i in range(1, N + 1):
	if A[i]:
		flag = 0
		break
if flag:
	print(answer)
else:
	print(-1)


from collections import defaultdict
from collections import deque
N = int(input())
A = [list(map(int, input().split(' '))) for i in [0] * N]
dic = defaultdict(int)
ns = [0] * N
ls = range(1, N + 1)
ans = 0
while True:
	new_ls = set([])
	for i in ls:
		if ns[i - 1] >= N - 1:
			continue
		j = A[i - 1][ns[i - 1]]
		dic[i * j, i + j] += 1
		if dic[i * j, i + j] == 2:
			new_ls.add(i)
			new_ls.add(j)
	if not new_ls:
		break
	for ind in new_ls:
		ns[ind - 1] += 1
	ls = new_ls
	ans += 1
for i in range(N):
	if ns[i] != N - 1:
		print(-1)
		exit()
print(ans)


import sys
read = sys.stdin.readline
n = int(read())
V = 1001000
g = [[] for _ in range(V)]
deg = [0] * V
vlist = set()
for i in range(1, n + 1):
	a = list(map(int, read().rstrip().split()))
	for j in range(n - 2):
		v1 = min(i, a[j]) * 1001 + max(i, a[j])
		v2 = min(i, a[j + 1]) * 1001 + max(i, a[j + 1])
		vlist.add(v1)
		vlist.add(v2)
		g[v1].append(v2)
		deg[v2] += 1
d = [0] * V
check_cnt = 0
q = []
for v in vlist:
	if deg[v] == 0:
		q.append(v)
if len(q) == 0:
	print(-1)
	exit()
for v in q:
	check_cnt += 1
	for nv in g[v]:
		d[nv] = max(d[nv], d[v] + 1)
		deg[nv] -= 1
		if deg[nv] == 0:
			q.append(nv)
if check_cnt == n * (n - 1) // 2:
	print(max(d) + 1)
else:
	print(-1)


import sys
N = int(input())
T = []
for i in range(N):
	a = [i - 1 for i in map(int, input().split())]
	T.append(a)
update = list(range(N))
ans = 0
L = [N - 1] * N
while True:
	K = []
	M = [0] * N
	for i in update:
		if L[i] != 0 and M[i] == 0:
			s = T[i][0]
			if L[s] != 0:
				if T[s][0] == i and M[s] == 0:
					K.append(i)
					K.append(s)
					M[i] = 1
					M[s] = 1
	for j in K:
		del T[j][0]
		L[j] -= 1
	if len(K) == 0:
		break
	ans += 1
	update = K
for i in range(N):
	if L[i] != 0:
		print(-1)
		sys.exit()
print(ans)


def MAP():
	return list(map(int, input().split()))
import collections
n = int(input())
a = [MAP() for _ in range(n)]
q = list(range(n))
c = collections.defaultdict(int)
t = [0] * n
r = 0
while q:
	r += 1
	nq = []
	for i in q:
		j = a[i][t[i]] - 1
		k = i
		if k < j:
			(j, k) = (k, j)
		c[j, k] += 1
		if c[j, k] == 2:
			t[j] += 1
			t[k] += 1
			if t[j] < n - 1:
				nq.append(j)
			if t[k] < n - 1:
				nq.append(k)
	q = nq
for tt in t:
	if tt != n - 1:
		print(-1)
		exit(0)
print(r)


N = int(input())
A = [None] * N
for i in range(N):
	A[i] = list(map(lambda x: int(x) - 1, input().split()))[::-1]
playable = set(range(N))
day = 0
while True:
	next_playable = set()
	done = set()
	for player in playable:
		if player in done:
			continue
		if len(A[player]) == 0:
			continue
		rival = A[player][-1]
		if rival in done:
			continue
		if len(A[rival]) == 0:
			continue
		if A[rival][-1] == player:
			done.add(player)
			done.add(rival)
			A[player].pop()
			A[rival].pop()
			next_playable.add(player)
			next_playable.add(rival)
	if len(next_playable) == 0:
		break
	playable = next_playable
	day += 1
ok = True
for i in range(len(A)):
	if len(A[i]) != 0:
		ok = False
		break
print((-1, day)[ok])


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)


import sys, collections
input = sys.stdin.readline
n = int(input())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
nums = [0 for i in range(n)]
day = 0
match = 0
flag = True
queue = collections.deque([])
temp = set()
for i in range(1, n + 1):
	i2 = a[i - 1][0]
	if a[i2 - 1][0] == i:
		if i not in temp:
			queue.append([i, i2])
			temp.add(i)
			temp.add(i2)
if not queue:
	flag = False
while queue:
	temp = []
	while queue:
		test = queue.popleft()
		match += 1
		(num1, num2) = (test[0], test[1])
		nums[num1 - 1] += 1
		nums[num2 - 1] += 1
		temp.append(num1)
		temp.append(num2)
	flag2 = False
	temp2 = set()
	for i in temp:
		if nums[i - 1] <= n - 2:
			new_num = a[i - 1][nums[i - 1]]
			if nums[new_num - 1] <= n - 2 and a[new_num - 1][nums[new_num - 1]] == i:
				if i not in temp2:
					queue.append([i, new_num])
					flag2 = True
					temp2.add(i)
					temp2.add(new_num)
	if flag2 == False and match < n * (n - 1) // 2:
		flag = False
		break
	day += 1
if flag == True:
	print(day)
else:
	print(-1)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
m = []
for i in range(n):
	a = list(map(int, input().split()))
	a.reverse()
	m.append(a)
ans = 0
count = 0
failflag = 0
previous = set()
for i in range(n):
	previous.add(i)
while count < n * (n - 1):
	ans += 1
	tempcount = count
	r = set()
	for i in previous:
		if m[i]:
			t = m[i][-1]
			if m[t - 1]:
				if m[t - 1][-1] == i + 1:
					count += 1
					r.add(i)
					r.add(t - 1)
	previous = set()
	for k in r:
		m[k].pop()
		previous.add(k)
		if m[k]:
			previous.add(m[k][-1] - 1)
	if tempcount == count:
		failflag = 1
		break
if failflag == 1:
	print(-1)
else:
	print(ans)


import sys
import re
import math
import collections
import decimal
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
ni = lambda : int(sys.stdin.readline())
ns = lambda : list(map(int, sys.stdin.readline().split()))
na = lambda : list(map(int, sys.stdin.readline().split()))
nb = lambda : list([int(x) - 1 for x in sys.stdin.readline().split()])

def main():
	n = ni()
	match = [collections.deque(nb()) for _ in range(n)]
	nxt = [-1] * n
	waiting = collections.deque(list(range(n)))
	cnt = [0] * n
	while len(waiting) > 0:
		ego = waiting.popleft()
		if len(match[ego]) == 0:
			continue
		enemy = match[ego].popleft()
		if nxt[enemy] == ego:
			waiting.append(ego)
			waiting.append(enemy)
			cnt[ego] = cnt[enemy] = max(cnt[ego], cnt[enemy]) + 1
		else:
			nxt[ego] = enemy
	if any(match):
		print(-1)
	else:
		print(max(cnt))

def __starting_point():
	main()
__starting_point()


from collections import deque
(N, *A) = map(int, open(0).read().split())
V = N * (N - 1) // 2
serial = [[0 for _ in range(N)] for _ in range(N)]
k = 0
for i in range(N):
	for j in range(i + 1, N):
		serial[i][j] = serial[j][i] = k
		k += 1
G = [[] for _ in range(V)]
deg = [0] * V
for (s, a) in zip(serial, zip(*[iter(A)] * (N - 1))):
	for j in range(N - 2):
		G[s[a[j] - 1]].append(s[a[j + 1] - 1])
		deg[s[a[j + 1] - 1]] += 1
Q = deque(((k, 1) for (k, v) in enumerate(deg) if v == 0))
ans = 0
cnt = len(Q)
while Q:
	(v, ans) = Q.popleft()
	for t in G[v]:
		deg[t] -= 1
		if deg[t] == 0:
			Q.append((t, ans + 1))
			cnt += 1
if cnt != V:
	print(-1)
else:
	print(ans)