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.



Sample input:
3
2 3
1 3
1 2


Sample output:
3

Submission status: Wrong Answer

Solution code:
N = int(input())
import sys
input = sys.stdin.readline
A = [None] * N
for i in range(N):
    a = list(map(int, input().split()))
    A[i] = a
    

def f():
    IDX = [0] * N
    day = 0
    end = 0
    while 1:
        IDX[:]
        flag = True
        for player, i in enumerate(IDX[:]):
            #print(player, i)
            if i > N-2:
                continue
            #print(player, i)
            enemy = A[player][i]

            if  A[enemy-1][IDX[enemy-1]] == player+1:
                IDX[player] += 1
                flag = False
                #print(player, NEXT_IDX)
                if IDX[player] == N-1:
                    end += 1
        if flag:
            #print(end, NEXT_IDX)
            return(-1)
        
        day += 1
        if end == N:
            return day

print(f())

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
A = [None] * N
for i in range(N):
    a = list(map(int, input().split()))
    A[i] = a[:]

vertex = {}
num = 0
for i, a in enumerate(A):
    i = i+1
    for j in a:
        _i, _j = min(i, j), max(i, j)
        key = "{}-{}".format(_i, _j) 
        if key in vertex:
            pass
        else:
            vertex[key] = num
            num += 1

#print(vertex)

from collections import deque
GRAY, BLACK = 0, 1
def topological(graph):
    order, enter, state = deque(), set(graph), {}

    def dfs(node, i):
        state[node] = GRAY
        ret = i+1
        for k in graph.get(node, ()):
            sk = state.get(k, None)
            if sk == GRAY: raise ValueError("cycle")
            if sk == BLACK: continue
            enter.discard(k)
            ret = max(ret, dfs(k, i+1))
        order.appendleft(node)
        state[node] = BLACK
        return ret

    ret = 0
    while enter: 
        ret = max(ret, dfs(enter.pop(), 0))
    return order, ret

graph = {v: [] for k, v in vertex.items()}
for i, a in enumerate(A):
    i = i+1
    pre = None
    for j in a:
        _i, _j = min(i, j), max(i, j)
        key = "{}-{}".format(_i, _j) 
        if pre == None:
            pre = vertex[key]
        else:
            cur = vertex[key]
            graph[pre].append(cur)
            pre = cur

#print(graph)
try:
    t, ans = topological(graph)
    print(ans)
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
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

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

    if v_len[id] != -1:
        return v_len[id]

    v_len[id] = 1

    for next in next_list:
        v_len[id] = max(v_len[id], dfs(next)+1)
    
    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:
    res = dfs(id)
    if res > len(index_list):
        ans = -1
        break
    ans = max(res, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

allList = []
days = 0

while len(allList) < N:
    allList.append(list(map(int, input().split())))

while True:
    toBePopped = []
    for i in range(N):
        if allList[i] and i+1 == allList[allList[i][0]-1][0]:
            toBePopped.append(i)
            toBePopped.append(allList[i][0]-1)
    if len(toBePopped) == 0:
        break
    days += 1
    for i in set(toBePopped):
        allList[i].pop(0)

if days == 0:
    print(-1)
else:
    print(days)

Submission status: Wrong Answer

Solution code:
n = int(input())
a_arr = []
for i in range(n):
    arr = list(map(int,input().split()))
    arr = arr[::-1]
    a_arr.append(arr)
day = [0]*n
for i in range(n):
    pre_day = day.copy()
    for j in range(n):
        if a_arr[j] == []:
            continue
        tmp = a_arr[j][-1] - 1
        if a_arr[tmp] != [] and a_arr[tmp][-1] == j + 1:
            a_arr[tmp].pop()
            a_arr[j].pop()
            day[j] = max(day[j], day[tmp]) + 1
            day[tmp] = day[j]
    if a_arr == [[] for _ in range(n)]:
        break
    if pre_day == day:
        print(-1)
        exit()
print(max(day))

Submission status: Wrong Answer

Solution code:
n = int(input())
a_arr = []
for i in range(n):
    a_arr.append(list(map(int,input().split())))
cnt = [0]*n
day = 0
jdg = [0]*n
for k in range(n + 1):
    pre_cnt = cnt.copy()
    for i in range(n):
        if cnt[i] == n -1 :
            continue
        tmp = a_arr[i][cnt[i]] - 1 
        if cnt[tmp] < n - 1 and a_arr[tmp][cnt[tmp]] == i + 1:
            cnt[i] += 1
            cnt[tmp] += 1
            day = max(jdg[i] + 1,jdg[tmp] + 1)
            jdg[i] = day
            jdg[tmp]  = day
    if pre_cnt == cnt:
        print(-1)
        exit()
    if cnt == [n-1]*n:
        break
print(max(jdg))

Submission status: Wrong Answer

Solution code:
n = int(input())
a_arr = []
for i in range(n):
    a_arr.append(list(map(int,input().split())))
cnt = [0]*n
day = 1
while (cnt != [n-1]*n):
    jdg = [0]*n
    for i in range(n):
        if jdg[i] != 0 or cnt[i] == n -1 :
            continue
        tmp = a_arr[i][cnt[i]] - 1 
        if cnt[tmp] < n - 1 and a_arr[tmp][cnt[tmp]] == i + 1:
            cnt[i] += 1
            cnt[tmp] += 1
            jdg[i] = 1
            jdg[tmp] = 1
    day += 1
    if day > (n-1)*n//2:
        print(-1)
        exit()
print(day)

Submission status: Wrong Answer

Solution code:
n = int(input())
a_arr = []
for i in range(n):
    a_arr.append(list(map(int,input().split())))
cnt = [0]*n
day = 0
while (cnt != [n-1]*n):
    jdg = [0]*n
    for i in range(n):
        if jdg[i] != 0 or cnt[i] == n -1 :
            continue
        tmp = a_arr[i][cnt[i]] - 1 
        if cnt[tmp] < n - 1 and a_arr[tmp][cnt[tmp]] == i + 1:
            cnt[i] += 1
            cnt[tmp] += 1
            jdg[i] = 1
            jdg[tmp] = 1
    day += 1
    if day > (n-1)*n//2:
        print(-1)
        exit()
print(day + 1)

Submission status: Wrong Answer

Solution code:

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
while next_set:
  day += 1
  current_set = next_set.copy()
  next_set = set()
  for match in current_set:
    del A[match[0]][-1]
    can_match(match[0], A, next_set)
    del A[match[1]][-1]
    can_match(match[1], A, next_set)

print(day)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = []
for i in range(N):
  A.append(deque(list(map(lambda x: int(x) - 1, input().split()))))
d = 0
B = [0]*N
Q = set(range(N))
while Q:
  Q2 = Q.copy()
  Q.clear()
  for i in Q2: 
    if len(A[i]) == 0 : continue
    vs = A[i][0]
    if len(A[vs]) == 0 : continue
    if A[vs][0] == i:
      Q.add(i)
      Q.add(vs)
      A[i].popleft()
      A[vs].popleft()
  for i in Q:
    B[i] += 1      
print (max(B)+1 if max(B) != 0 else -1)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = []
for i in range(N):
  A.append(deque(list(map(lambda x: int(x) - 1, input().split()))))
C = [-1]*N
d = 1
cnt = 0
max = N * (N-1) // 2
while cnt < max:
  f = False
  for i in range(N):
 
    if len(A[i]) == 0 : continue
    vs = A[i][0]
    if len(A[vs]) == 0 : continue
    if A[vs][0] == i and C[i] != d:
      A[i].popleft()
      A[vs].popleft()
      C[i] = d
      C[vs] = d
      cnt += 1
      f = True
  if not f:
    print (-1)
    break
  d += 1
else:
  print (d)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = []
for i in range(N):
  A.append(deque(list(map(lambda x: int(x) - 1, input().split()))))
C = [-1]*N
d = 1
cnt = 0
max = N * (N-1) // 2
while cnt < max:
  f = False
  for i in range(N):
 
    if len(A[i]) == 0 : continue
    vs = A[i][0]
    if len(A[vs]) == 0 : continue
    if A[vs][0] == i and C[i] != d:
      A[i].popleft()
      A[vs].popleft()
      C[i] = d
      C[vs] = d
      cnt += 1
      f = True
  if not f:
    print (-1)
    break
  print (A)
  d += 1
else:
  print (d)

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input().rstrip("\n"))

    opposites = {}
    for id in range(1, n + 1):
        opposites[id] = [int(x) for x in input().rstrip("\n").split(" ")]
    ids = list(range(1, n + 1))
    
    from collections import defaultdict
    edges = defaultdict(list)
    
    for id in ids:
        prev_opposite = None
        for opposite in opposites[id]:
            if prev_opposite:
                edges[id ** 2 + opposite ** 2].append(id ** 2 + prev_opposite ** 2)
            prev_opposite = opposite
    #print(opposites)
    #print(edges)
    result = check_loop(ids, edges, opposites)
    if result == -1:
        print(-1)
    else:
        print(result)
        
    
    
def check_loop(ids, edges, opposites):
    from collections import defaultdict
    
    marks = defaultdict(str)
    depths = defaultdict(int)
    results = []
    for id in ids:
        last_node = id**2 + opposites[id][-1]**2
        result = check_mark(last_node, edges, marks, depths)
        if result == -1:
            return -1
        results.append(result)
    return max(results)

def check_mark(node, edges, marks, depths):
    
    if marks[node] == "ACTIVE":
        return -1
    if marks[node] == "FINISHED":
        return depths[node]
    marks[node] = "ACTIVE"
    
    results = []
    for next_node in edges[node]:
        result = check_mark(next_node, edges, marks,depths)
        if result == -1:
            return -1
        results.append(result)
    
    marks[node] = "FINISHED"
    if results:
        depths[node] = max(results) + 1
    else:
        depths[node] = 1
    return depths[node]

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def is_equal_N(input_num):
    if input_num == N-1:
        return True
    else:
        return False


N = int(input())
A = [list(map(int, input().split())) for i in range(N)]
match_cnt = [0 for i in range(N)]
false_cnt = 0
result = 1
match_opp = 0

while True:
    false_cnt = 0

    if all(map(is_equal_N, match_cnt)):
        break

    for i in range(N):
        try:
            match_opp = A[i][match_cnt[i]] - 1
            if (i == (A[match_opp][match_cnt[match_opp]] - 1)):
                match_cnt[i] += 1
                match_cnt[match_opp] += 1
            else:
                false_cnt += 1
        except:
            false_cnt += 1

    if false_cnt == N:
        result = -1
        break

    result += 1

print(result)

Submission status: Wrong Answer

Solution code:
N = int(input())
orders = [] #試合順

for i in range(N):
    orders.append([int(j) for j in input().split()])

next_index = []
for i in range(N):
    next_index.append([0, False])
remains = []
for i in range(N):
    remains.append(i+1)
days = 0
is_possible = True
finished = 0

while len(remains) > 0:
    #1day process
    trued_i = []
    for i, e in enumerate(remains):
        #相手の相手が自分であり、1日の処理をまだしていない場合、対戦処理
        opponent = orders[e-1][next_index[e-1][0]]
        oppo_oppo = orders[opponent-1][next_index[opponent-1][0]]
        if oppo_oppo == e:
            if not (next_index[e-1][1] or next_index[opponent-1][1]):
                ni_e_0 = next_index[e-1][0]
                ni_o_0 = next_index[opponent-1][0]
                ni_e_0 += 1
                ni_o_0 += 1
                next_index.pop(e-1)
                next_index.insert(e-1,[ni_e_0, True])
                next_index.pop(opponent-1)
                next_index.insert(opponent-1, [ni_o_0, True])
                trued_i.append(e)
                trued_i.append(opponent)
                #カンストしたか
                if ni_e_0 >= N-1:
                    remains.remove(e)
                if ni_o_0 >= N-1:
                    remains.remove(opponent)
    days += 1
    #TrueをFalseに
    for i, e in enumerate(trued_i):
        ni_e_0 = next_index[e-1][0]
        next_index.pop(e-1)
        next_index.insert(e-1,[ni_e_0, False])

    if days > N * (N-1) // 2:
        is_possible = False
        break

if is_possible:
    print(days)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
N = int(input())
A=[]
for j in range(N): 
    A.append([int(i) for i in input().split()])
    
for list in A:
    list.reverse()

day = 0
empty = 0

#whileループ一回を一日と考える
while N==N:
    #print(A)
    q = []
    day +=1
    for i in range(N):
        #print(A)
        #print(i)
        #i行目が空なら空であることを示すemptyリストを1に
        if len(A[i]) == 0:
            empty = empty+1
        #iが既にqに入っていればパス
        elif i in q:
            pass
        #i行目の末尾の数字で示された相手方が一致していればキューに追加
        elif int(A[int(A[i][-1])-1][-1]) == i+1:
                #print(i, int(A[i][-1]))
                q.append(i)
                q.append(int(A[i][-1])-1)
    #ループ後にqが空ならそれ以上進めないので判定
    if len(q) == 0:
        if empty == N:
            print(day-1)
            exit()
        else:
            print(-1)
            exit()
    #そうでなければキューに追加されている行の末尾を削除する
    else:
        for d in q:
            #print(d)
            A[d].pop(-1)

Submission status: Wrong Answer

Solution code:
N = int(input())
A=[]
for j in range(N): 
    A.append([int(i) for i in input().split()])
    
for list in A:
    list.reverse()

day = 0
empty = [0] * N 

#whileループ一回を一日と考える
while N==N:
    #print(A)
    q = []
    day +=1
    for i in range(N):
        #print(A)
        #print(i)
        #i行目が空なら空であることを示すemptyリストを1に
        if len(A[i]) == 0:
            empty[i] = 1
        #iが既にqに入っていればパス
        elif i in q:
            pass
        #i行目の末尾の数字で示された相手方が一致していればキューに追加
        elif int(A[int(A[i][-1])-1][-1]) == i+1:
                #print(i, int(A[i][-1]))
                q.append(i)
                q.append(int(A[i][-1])-1)
    #ループ後にqが空ならそれ以上進めないので判定
    if len(q) == 0:
        if sum(empty) == N:
            print(day)
            exit()
        else:
            print(-1)
            exit()
    #そうでなければキューに追加されている行の末尾を削除する
    else:
        for d in q:
            #print(d)
            A[d].pop(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque, defaultdict
import copy
import bisect
#sys.setrecursionlimit(10 ** 9)
import math
import heapq

import sys
def input():
	return sys.stdin.readline().strip()


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

graph = [[[] for j in range(N)] for i in range(N)]
day = [[1 for j in range(N)] for i in range(N)]


for i in range(N):
	for j in range(N - 1):
		if j != N - 2:
			graph[min(i, A[i][j] - 1)][max(i, A[i][j] - 1)].append([min(i, A[i][j + 1] - 1), max(i, A[i][j + 1] - 1)])

que = deque([])
for i in range(N):
	if A[A[i][0] - 1][0] - 1 == i and i < A[i][0] - 1:
		que.append([i, A[0][i] - 1])

day_max = 1
if len(que) == 0:
	print(-1)
	exit()
while len(que) > 0:
	match = que.popleft()
	for path in graph[match[0]][match[1]]:
		if day[match[0]][match[1]] + 1 > day[path[0]][path[1]]:
			day[path[0]][path[1]] = day[match[0]][match[1]] + 1
			day_max = max(day_max, day[path[0]][path[1]])
			que.append(path)
	if day_max > N*(N-1)//2:
		print(-1)
		exit()

print(day_max)

Submission status: Wrong Answer

Solution code:
N = int(input())
orders = [] #試合順

for i in range(N):
    orders.append([int(j) for j in input().split()])

next_index = []
for i in range(N):
    next_index.append([0, False])
remains = []
for i in range(N):
    remains.append(i+1)
days = 0
is_possible = True
finished = 0

while len(remains) > 0:
    #1day process
    for i, e in enumerate(remains):
        #相手の相手が自分であり、1日の処理をまだしていない場合、対戦処理
        opponent = orders[e-1][next_index[e-1][0]]
        oppo_oppo = orders[opponent-1][next_index[opponent-1][0]]
        if oppo_oppo == e:
            if not (next_index[e-1][1] or next_index[opponent-1][1]):
                ni_e_0 = next_index[e-1][0]
                ni_o_0 = next_index[opponent-1][0]
                ni_e_0 += 1
                ni_o_0 += 1
                next_index.pop(e-1)
                next_index.insert(e-1,[ni_e_0, True])
                next_index.pop(opponent-1)
                next_index.insert(opponent-1, [ni_o_0, True])
                #カンストしたか
                if ni_e_0 >= N-1:
                    remains.remove(e)
                if ni_o_0 >= N-1:
                    remains.remove(opponent)
    days += 1
    #TrueをFalseに
    for i in range(N):
        ni_i_0 = next_index[i][0]
        next_index.pop(i)
        next_index.insert(i, [ni_i_0, False])

    if days > N * (N-1) // 2:
        is_possible = False
        break

if is_possible:
    print(days)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
from collections import deque

N = int(input())
ad = [[] for _ in range(N**2)]
num = [0] * (N**2)
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]
        ti, tj = min(i, j), max(i, j)
        nti, ntj = min(i, nj), max(i, nj)
        v = N*ti + tj
        nv = N*nti + ntj
        ad[v].append(nv)
        num[nv] += 1

L = []
S = deque()

for v in range(N**2):
    i, j = divmod(v, N)
    if i >= j:
        continue
    if num[v] == 0:
        S.append(v)

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

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

cand_list = []

dp = [-1] * (N**2)

def dfs(v):
    if dp[v] != -1:
        return dp[v]
    res = 1
    for nv in ad[v]:
        res = max(res, dfs(nv) + 1)
    dp[v] = res
    return res

ans = dfs(L[0])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
from collections import deque

N = int(input())
ad = [[] for _ in range(N**2)]
num = [0] * (N**2)
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]
        ti, tj = min(i, j), max(i, j)
        nti, ntj = min(i, nj), max(i, nj)
        v = N*ti + tj
        nv = N*nti + ntj
        ad[v].append(nv)
        num[nv] += 1

L = []
S = deque()

for v in range(N**2):
    i, j = divmod(v, N)
    if i >= j:
        continue
    if num[v] == 0:
        S.append(v)

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

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

cand_list = []

visited = [0] * (N**2)

def dfs(v):
    res = 1
    visited[v] = 1
    for nv in ad[v]:
        if not visited[nv]:
            res = max(res, dfs(nv) + 1)
    return res

ans = dfs(L[0])
print(ans)

Submission status: Wrong Answer

Solution code:
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
                # parent_node[now_tuple] += 0
            else:
                index = get_ind(pre_tuple, num)
                # print(index, pre_tuple)
                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.pop()
        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()

Submission status: Wrong Answer

Solution code:
n = int(input())
a = [list(map(int, input().split(' ')))]
for i in range(n-1):
    a.append(list(map(int, input().split(' '))))
X = []
next = [0]*n
game = [0]*n
for i in range(n-1):
    X.append([0]*(n-1-i))
x = X
for k in range(int(n*(n-1)/2)+1):
    g = game
    hantei = 0
    h = 0
    for ii in a:
        if len(ii) != 0:
            h = 1
            break
    if h == 0:
        print(k)
        exit()
    for i, b in enumerate(a):
        if b == [] or g[i] == 1 or next[i] == 1:
            continue
        j = b[0] - 1
        if i < j:
            x[i][j-i-1] += 1   
            if x[i][j-i-1] == 2:
                a[i].pop(0)
                a[j].pop(0)
                next[i] = 0
                next[j] = 0
                g[i] = 1
                g[j] = 1
                hantei = 1
            else:
                next[i] = 1

        else:
            x[j][i-j-1] += 1
            if x[j][i-j-1] == 2:
                a[i].pop(0)
                a[j].pop(0)
                next[i] = 0
                next[j] = 0
                g[i] = 1
                g[j] = 1  
                hantei = 1
            else:
                next[i] = 1
    if hantei == 0:
        print(-1)
        exit()

Submission status: Wrong Answer

Solution code:
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
                # parent_node[now_tuple] += 0
            else:
                index = get_ind(pre_tuple, num)
                # print(index, pre_tuple)
                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.pop()
        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()

Submission status: Wrong Answer

Solution code:
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
                # parent_node[now_tuple] += 0
            else:
                index = get_ind(pre_tuple, num)
                # print(index, pre_tuple)
                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):
        now_node, length = q.pop()
        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()

Submission status: Wrong Answer

Solution code:
N = int(input())

A = []
for i in range(N):
  A.append(list(map(lambda x: int(x) - 1, input().split())))
B = [0 for i in range(N)]
C = [0 for i in range(N)]
d = 1
cnt = 0
while cnt < N * (N-1) // 2:
  f = False
  for i in range(N):
    if B[i] >= N - 1: continue
    vs = A[i][B[i]]
    if vs >= N - 1: continue

    if A[vs][B[vs]] == i and C[i] != d and C[vs] != d:
      B[vs] += 1
      C[vs] = d
      B[i] += 1
      C[i] = d
      cnt += 1
      f = True
  if not f: 
    print (-1)
    break
  d += 1
else:
  print ( -1 if len(B) < 0 else d)

Submission status: Wrong Answer

Solution code:
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


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
                # parent_node[now_tuple] += 0
            else:
                index = get_ind(pre_tuple, num)
                # print(index, pre_tuple)
                graph_data[index].add(now_tuple)
                index2 = get_ind(now_tuple, num)
                parent_node[index2] += 1
            pre_tuple = now_tuple

    q = queue.Queue()
    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.put((node, 1))
                count_node += 1
    sys.exit()
    
    while not q.empty():
        now_node, length = q.get()
        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.put((next_node, length + 1))
                count_node += 1

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







if __name__ == '__main__':
    main()