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:
#import numpy as np
#from numpy import*
#from scipy.sparse.csgraph import shortest_path #shortest_path(csgraph=graph) # dijkstra# floyd_warshall
#from scipy.sparse import csr_matrix
 
from collections import* #defaultdict Counter deque appendleft
from fractions import gcd
from functools import* #reduce
from itertools import* #permutations("AB",repeat=2) combinations("AB",2) product("AB",2) groupby accumulate
from operator import mul,itemgetter
from bisect import* #bisect_left bisect_right
from heapq import* #heapify heappop heappushpop
from math import factorial,pi
from copy import deepcopy
import sys
sys.setrecursionlimit(10**8)
#input=sys.stdin.readline  #危険！基本オフにしろ！
 
def main():
    n=int(input())
    d=defaultdict(deque)
    for i in range(n):
        d[i+1]=deque(map(int,input().split()))
    #print(d)
    
    c=0
    while any(len(i)>0 for i in d.values()):
        c+=1
        skip=set()
        for i in range(1,n+1):
            if i not in skip.copy():
                if d[i]:
                    oppo=d[i].popleft()
                    if oppo in skip:
                        d[i].appendleft(oppo)
                        continue
                    if i!=d[oppo].popleft():
                        print(-1)
                        exit()
                    else:
                        skip.add(oppo)
                        skip.add(i)
                else:
                    continue
            #else:
                #print("skip")
            #print(c,i,d)
    print(c)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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


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


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


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


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


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


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


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


def mt(f):
    import time

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

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

    return wrap


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

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

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

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


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

    # N = 1000
    # A = []

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# E - League
N = int(input())

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

print(N)

Submission status: Wrong Answer

Solution code:
import os
from itertools import chain
N = int(input())
a_list = [ list(map(int, input().split())) for i in range(N)]

cost_list = [[-1 for _ in range(N)]for _ in range(N)]

for i in range(N):
    for j in range(N-1):
        b = a_list[i][j]-1
        res = max(cost_list[i][b], cost_list[b][i], j)
        cost_list[i][b] = res
        cost_list[b][i] = res

game_list = [[] for i in range(N-1)]

for i in range(N):
    for j in range(i+1, N):
        game_list[cost_list[i][j]].append([i, j])

cnt = 0
for games in game_list:
    if len(games) == 0:
        print(-1)
        os.sys.exit()
    s = list(chain.from_iterable(games))
    s.sort()
    stack = 1
    max_stack = 0
    for i in range(1, len(s)):
        if s[i-1] == s[i]:
            stack += 1
            if i == len(s) - 1 and stack > max_stack:
                max_stack = stack
        else:
            if stack >= max_stack:
                max_stack = stack
            stack = 1
    cnt += max(1, max_stack)

print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())

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

c = 0
z_list = [i for i in range(N)]
while(1):
    alr_list = []
    for i in z_list:
        if i in alr_list:
            continue
        i_a = a_list[i][0] - 1
        if i_a in alr_list:
            continue

        if i+1 == a_list[i_a][0]:
            a_list[i].pop(0)
            a_list[i_a].pop(0)
            if len(a_list[i]) == 0:
                z_list.remove(i)
            if len(a_list[i_a]) == 0:
                z_list.remove(i_a)
            alr_list.append(i)
            alr_list.append(i_a)
    c += 1
    if len(z_list) == 0:
        break
    if len(alr_list) == 0:
        c = -1
        break
print(c)

Submission status: Wrong Answer

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import bisect
from collections import deque

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

def LI(): return list(map(int, sys.stdin.readline().split()))


N = int(input())
A = [[] for i in range(N)]
for i in range(N):
    A[i] = LI()
    for j in range(len(A[i])):
        A[i][j] -= 1

# positions = [0 for i in range(N)]
match = 1
ans = 0
while match:
    ans += 1
    match = 0
    for i in range(N):
        if len(A[i]) == 0:
            pass
        else:
            enemy = A[i][0]
            if A[enemy][0] == i:
                A[enemy].pop(0)
                A[i].pop(0)
                match = 1
for i in range(N):
    if len(A[i]) != 0:
        print(-1)
        exit()

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
a_list = [None for _ in range(n)]
num = 0
day = 0
for i in range(n):
    a_list[i] = deque([int(i) - 1 for i in input().split()])

while (num < n * (n - 1) // 2):
    visit = set([])
    day += 1
    for j in range(n):
        if j not in visit:
            if len(a_list[j]) > 0:
                k = a_list[j][0]
                if k not in visit:
                    if a_list[k][0] == j:
                        num += 1
                        visit.union({k, j})
                        a_list[k].popleft()
                        a_list[j].popleft()
    if (len(visit) == 0):
        day = -1
        break
print(day)

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    a = [list(map(int, input().rstrip('\n').split())) for _ in range(n)]
    ls = [0] * n
    mt = [0] * n
    cnt = 0
    bbb = 0
    # 初回のみセット
    for i in range(n):
        if ls[i] != -1:
            mt[i] = a[i][ls[i]]

    for w in range(10 ** 15):
        cnt += 1
        f = [False] * n
        bb = False
        for i in range(n):
            if not f[i]:
                if ls[i] != -1:
                    if i + 1 == mt[mt[i] - 1]:
                        if ls[i] + 1 < n - 1:

                            ls[i] += 1
                            mt[i] = a[i][ls[i]]
                            f[i] = True

                            if ls[mt[i] - 1] < n - 1:
                                ls[mt[i] - 1] += 1
                                mt[mt[i] - 1] = a[i][ls[mt[i] - 1]]
                                f[mt[i] - 1] = True
                            
                            bb = True
                        else:
                            ls[i] = -1
                            bbb += 1
        if bbb == n:
            print(cnt)
            exit()
        if not bb:
            print(-1)
            exit()


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
n=int(input())
alist=[]
nowlist=[]
klist=[]
nextlist=[]
incre=0
error=0
day=0

for i in range(n):
    alist.append(list(map(int, input().split())))

for i in range(n):
    nowlist.append(0)
    nextlist.append(-1)

while error==0 and incre<n*(n-1):
    swit=0
    for i in range(n):
        if nowlist[i]<n-1:
            #プレイヤーiはalist[i][nowlist[i]]-1と戦う
            #nowlist[i]でその人の進行具合が分かる
            nextlist[i]=alist[i][nowlist[i]]-1
            #print(i, nextlist[alist[i][nowlist[i]]-1])
            if nextlist[alist[i][nowlist[i]]-1]==i:
                nextlist[alist[i][nowlist[i]]-1]=-1
                nowlist[alist[i][nowlist[i]]-1]+=1
                nowlist[i]+=1
                incre+=2
                swit=1
    day+=1
    if swit==0:
        day=-1
        error=1

print(day)

Submission status: Wrong Answer

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

t = N * (N-1) // 2
m = [[0 for _ in range(N)] for __ in range(t+1)]

end = 0
for d in range(t):
    if end == N:
        print(d)
        break
    n = 0
    for p1 in range(N):
        i1 = m[d][p1]
        if i1 == N - 1:
            m[d+1][p1] = i1
            continue
        p2 = A[p1][i1] - 1
        i2 = m[d][p2]
        if i2 == N - 1:
            m[d+1][p1] = i1
            continue
        if m[d+1][p1] == i1 + 1:
            continue
        if m[d+1][p2] == i2 + 1:
            m[d+1][p1] = i1
            continue
        if A[p2][i2] - 1 == p1:
            m[d+1][p1] = i1 + 1
            if i1 + 1 == N - 1:
                end += 1
            m[d+1][p2] = i2 + 1
            if i2 + 1 == N - 1:
                end += 1
            n += 1
    if n == 0:
        print(-1)
        break
else:
    print(t)

Submission status: Wrong Answer

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

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

NN=(N*(N-1))//2
edges=[[] for _ in range(NN)]
nums = [0]*NN
for i in range(N):
    sis=[0]*(N-1)
    for j in range(N-1):
        src, dst = sorted([i,A[i][j]-1])
        sis[j] = inds[src][dst]

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

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

if len(arr) == 0:
    print(-1)
    exit()

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

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    a = [list(map(int, input().rstrip('\n').split())) for _ in range(n)]
    ls = [0] * n
    mt = [0] * n
    cnt = 0
    bbb = 0
    # 初回のみセット
    for i in range(n):
        if ls[i] != -1:
            mt[i] = a[i][ls[i]]

    for w in range(10 ** 15):
        cnt += 1
        f = [False] * n
        bb = False
        for i in range(n):
            if not f[i]:
                if ls[i] != -1:
                    if i + 1 == mt[mt[i] - 1]:
                        if ls[i] + 1 < n - 1:
                            
                            ls[i] += 1
                            ls[mt[i] - 1] += 1
                            mt[i] = a[i][ls[i]]
                            mt[mt[i] - 1] = a[i][ls[mt[i] - 1]]
                            f[i] = True
                            f[mt[i] - 1] = True
                            
                            bb = True
                        else:
                            ls[i] = -1
                            bbb += 1
        if bbb == n:
            print(cnt)
            exit()
        if not bb:
            print(-1)
            exit()


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
N = int(input())

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

# check = [[True] + [False] * (N - 2) for _ in range(N)] #True準備完了、False試合不可
check = [0] * N #i番目の次の相手のindex

ans = 0
i = 0
tmp = 0
count = 0
while tmp < N + 5:
    if i % N == 0:
        ans += 1
        flag  = [True] * N #試合をしたかどうかチェック
        i = 0
    if check[i] >= N - 1:
        i += 1
        tmp += 1
        continue
    if flag[i] == False: #試合済みのとき
        i += 1
        tmp += 1
        continue
    b = A[i][check[i]]
    # print (b)
    if A[b - 1][check[b - 1]] - 1 == i and flag[b - 1] == True: #試合できる時
        check[i] += 1
        check[b - 1] += 1
        flag[i] = False
        flag[b - 1] = False
        tmp = 0
        count += 1
    i += 1
    tmp += 1
    if count == (N * (N - 1))//2:
        break
    # print (check)

# print (check)
for i in check:
    if i != N - 1:
        print (-1)
        exit()

print (ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys
input = sys.stdin.readline

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

progress_list = [0] * N
next_list = [a[0] for a in A]
done_match = 0

day_limit = N * (N - 1) // 2
for i in range(day_limit):
    exhausted = [0] * N

    for man_idx in range(N):
        if progress_list[man_idx] >= N - 1:
            continue
        opponent_idx = A[man_idx][progress_list[man_idx]] - 1
        if exhausted[opponent_idx] or opponent_idx < man_idx:
            continue

        if progress_list[opponent_idx] >= N - 1:
            continue
        opponents_opponent = A[opponent_idx][progress_list[opponent_idx]] - 1
        if man_idx == opponents_opponent:
            # print('day', i + 1, ',', man_idx + 1, opponent_idx + 1)
            progress_list[man_idx] += 1
            # exhausted[man_idx] += 1
            progress_list[opponent_idx] += 1
            exhausted[opponent_idx] += 1
            done_match += 1

    if done_match == day_limit:
        print(i + 1)
        exit()

else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
dic = {}
for i in range(N):
  a = [int(i) for i in input().split()]
  dic[i+1] = deque(a[:])
count = 0
while True:
  nokori = 0
  flag = True
  for k in dic.keys():
    log = [-1]*N
    k = int(k)
    if dic[k]==deque([]):
      nokori += 1
      continue
    p2 = dic[k][0]
#    print(k,p2)
    if dic[p2]==deque([]):
      print(-1)
      break
    if dic[p2][0]==k and log[k-1]==-1 and log[p2-1]==-1:
      a = dic[k].popleft()
      b = dic[p2].popleft()
#      print('%', a,b)
      log[k-1] = 1
      log[p2-1] = 1
      flag = False
  count += 1
      
  if nokori == N:
    print(count)
    break
  elif flag:
    print(-1)
    break

Submission status: Wrong Answer

Solution code:
from collections import deque
n=int(input())
data=[deque(map(int,input().split())) for i in range(n)]
count=[[0]*(n-1) for i in range(n)]
last=n*(n-1)
count=0
while last:
	flag=0
	count+=1
	taisenzumi=[]
	for i in range(n):
		if i in taisenzumi:continue
		if data[i]:
			aite=data[i][0]
			# print(data[i],aite)
			if (aite-1) in taisenzumi:continue
			# print(data[i],aite)
			if data[aite-1][0]==i+1:
				data[i].popleft()
				data[aite-1].popleft()
				taisenzumi.append(aite-1)
				taisenzumi.append(i)
				last-=2
				flag=1
			else:continue
	if not flag:
		break
	print(last)
else:
	print(count)
	exit()
print(-1)

Submission status: Wrong Answer

Solution code:
import sys
n = int(input())
a = [[int(i) for i in input().split()] for j in range(n)]

for i in range(n-1):
    for j in range(n):
        k = a[j][i] - 1
        if a[k][i] - 1 == j:
            print(n)
            sys.exit(0)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys, time
def input():
	return sys.stdin.readline()[:-1]

n = int(input())
a = [list(map(int, input().split()))[::-1] for _ in range(n)]
#print(*a, sep="\n")
opponent = [-1 for _ in range(n)]
match = 0
day = 0
start_time = time.time()
while match < n*(n-1)//2:
	approved = False
	for i in range(n):
		if a[i] != [] and opponent[i] == -1:
			opponent[i] = a[i].pop()-1
	#print(opponent)
	for i in range(n):
		if opponent[i] != -1 and opponent[opponent[i]] == i:
			approved = True
			match += 1
			opponent[opponent[i]] = -1
			opponent[i] = -1
	#print(opponent)
	if not approved:
		print(-1)
		sys.exit()
	now = time.time()
	#print(start_time, now, now - start_time)
	if now-start_time > 1.5:
		print(-1)
		sys.exit()
	day += 1
print(day)

Submission status: Wrong Answer

Solution code:
n=int(input())
alist=[]
nowlist=[]
klist=[]
poplist=[]
nextlist=[]
incre=0
error=0
day=0

for i in range(n):
    alist.append(list(map(int, input().split())))

for i in range(n):
    nowlist.append(0)
    poplist.append(i)
    nextlist.append(-1)

koho=[]
#print(nowlist)

while error==0 and incre<n*(n-1):
    swit=0
    for i in range(n):
        if nowlist[i]<n-1:
            #プレイヤーiはalist[i][nowlist[i]]-1と戦う
            #nowlist[i]でその人の進行具合が分かる
            nextlist[i]=alist[i][nowlist[i]]-1
            #print(i, nextlist[alist[i][nowlist[i]]-1])
            if nextlist[alist[i][nowlist[i]]-1]==i:
                nowlist[alist[i][nowlist[i]]-1]+=1
                nextlist[alist[i][nowlist[i]]-1]=-1
                nowlist[i]+=1
                incre+=2
                swit=1
    day+=1
    if swit==0:
        day=-1
        error=1

print(day)

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()

n = ni()
li = []
a = [[] for i in range(n-1)]
for i in range(n):
    aaa = na()
    li.append(aaa)
    for j in range(len(aaa)):
        a[j].append(aaa[j])
for i in range(n-1):
    a[i].sort()
flag = False
ans = n
for i in range(n-1):
    for j in range(i+1, n-1):
        if a[i] == a[j]:
            ans = -1
            flag = True
            break
    if flag:
        break
print(ans)

Submission status: Wrong Answer

Solution code:
def getlist():
	return list(map(int, input().split()))

X = []
N = int(input())
for i in range(N):
	A = getlist()
	X.append([10 ** 5] + A[::-1])

#日数
day = 0
judge = "Yes"
while True:
	j = "No"
	check = [0] * N
	for i in range(N):
		x = X[i][-1]
		if check[i] == 0 and x != 10 ** 5:
			if X[x - 1][-1] == i + 1:
				check[x - 1] = 1
				X[x - 1].pop(-1)
				X[i].pop(-1)
				j = "Yes"
	day += 1
	if j == "No":
		break

#判定
cc = "Yes"
for i in range(N):
	if X[i] != [10 ** 5]:
		cc = "No"
		break

if cc == "No":
	day = -1


print(day)

Submission status: Wrong Answer

Solution code:
def topological_sort(E, D):
    D = D[:]
    n = len(E)
    Q = [i for i in range(n) if D[i] == 0]
    L = []
    while Q:
        p = Q.pop()
        L.append(p)
        for vf in E[p]:
            D[vf] -= 1
            if not D[vf]:
                Q.append(vf)
    
    if len(L) != n:
        return False
    return L

N = int(input())

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

Aidx = [None]*N

for i in range(N):
    d = [None]*N
    for j in range(N-1):
        aj = A[i][j]
        d[aj] = j
    Aidx[i] = d[:]

L = N*N
Edge = [[] for _ in range(L)]
Dim = [0]*L

for i in range(N):
    for j in range(i+1, N):
        t = i*N+j
        a = Aidx[i][j]
        
        if a != N-2:
            ki = A[i][a+1]
            p = min(i*N + ki, ki*N+i)
            Edge[t].append(p)
            Dim[p] += 1


        b = Aidx[j][i]
        if b != N-2:
            kj = A[j][b+1]
            q = min(j*N+kj, kj*N+j)
            Edge[t].append(q)
            Dim[q] += 1

order = topological_sort(Edge, Dim)

if order == False:
    print(-1)
else:
    ans = 1
    used = set()
    for k in order:
        i, j = divmod(k, N)
        if i >= j:
            continue
        if i in used or j in used:
            ans += 1
            used = set([i, j])
        else:
            used.add(i)
            used.add(j)
    print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
n=int(input().rstrip())
a=[]

cnt=[]
for i in range(n):
    cnt.append(0)
    a.append(input().rstrip().split(" "))
    for j in range(n-1):
        a[i][j]=int(a[i][j])
ans=0;
day=0

while(a==[]):
    oa=a
    day=day+1
    for i in range(n):
        cnt[i]=0
    for i in range(n-1):
        if(cnt[i]==1):
            continue
        else:
            s=a[i][0]
            if i+1==a[s][0] and s==a[i][0]  and cnt[s-1]==0:
                cnt[i-1]=1
                cnt[s-1]=1
                del a[i][0]
                del a[s-1][0]
    if(oa==a):
        day=-1
        break
    
print(day)

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**9)
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
a = []
for i in range(n):
    b = na()
    a.append(list(reversed(b)))
i = 1
while i < n*(n-1)//2:
    f = -1
    for j in range(n):
        if len(a[j]) == 0:
            continue
        f = 0
        if a[a[j][-1]-1][-1]-1 == j:
            a[a[j][-1]-1].pop()
            a[j].pop()
            f = 1
    if f == 0:
        print(-1)
        exit()
    if f == -1:
        break
    i += 1

print(i)

Submission status: Wrong Answer

Solution code:
import numpy as np

n = int(input())
a = []
for i in range(n):
    ai = list(map(int, input().split()))
    a.append(ai)

ind = [0 for i in range(n)]
ind_copy = ind.copy()

a = np.array(a)
a = a - 1

ans = 0
while True:
    kanou = 0
    ans += 1
    for i in range(n):
        if ind[i] <= n-2:
            player = a[i][ind[i]]
        else:
            break
        if ind[player] <= n-2:
            player_vs = a[player][ind[player]]
        else:
            break
        if i == player_vs:
            kanou = 1
            ind_copy[i] = ind[i] + 1
            ind_copy[player] = ind[player] + 1
    if kanou == 0:
        hantei = 0
        for i in range(n):
            if ind[i] < n-2:
                hantei = 1
        if hantei == 1:
            ans = -1
        break
    ind = ind_copy.copy()

print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
ct=[0 for i in range(n)]
fin=0
day=0

while sum(ct)!=n*(n-1) and day<=3*n:
  L=[0 for i in range(n)]
  for i in range(n):
    if L[i]==0 and ct[i]!=n-1:
      x=l[i][ct[i]]
      if l[x-1][ct[x-1]]-1==i and L[x-1]==0:
        ct[i]+=1
        ct[x-1]+=1
        L[i]=1
        L[x-1]=1
  day+=1
if day<=3*n:
  print(day)
else:
  print(-1)

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    a = [list(map(int, input().rstrip('\n').split())) for _ in range(n)]
    ls = [0] * n
    mt = [0] * n
    cnt = 0
    bbb = 0
    #初回のみセット
    for i in range(n):
        if ls[i] != -1:
            mt[i] = a[i][ls[i]]
            
    for w in range(10 ** 15):
        cnt += 1
        f = [False] * n
        bb = False
        for i in range(n):
            if not f[i]:
                if ls[i] != -1:
                    if i + 1 == mt[mt[i]-1]:
                        if ls[i] + 1 < n - 1:
                            ls[i] += 1
                            mt[i] = a[i][ls[i]]
                            bb = True
                        else:
                            ls[i] = -1
                            bbb += 1
        if bbb == n:
            print(cnt)
            exit()
        if not bb:
            print(-1)
            exit()


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
a_list = [None for _ in range(n)]
num = 0
day = 1
for i in range(n):
    a_list[i] = deque([int(i) - 1 for i in input().split()])

while (num < n * (n - 1) // 2):
    visit = set([])
    day += 1
    for j in range(n):
        if j not in visit:
            if len(a_list[j]) > 0:
                k = a_list[j][0]
                if k not in visit:
                    if a_list[k][0] == j:
                        num += 1
                        visit.add(a_list[j].popleft())
                        visit.add(a_list[k].popleft())
    if ((j == n - 1) & (len(visit) == 0)):
        day = -1
        break
print(day)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
a_list = [None for _ in range(n)]
num = 0
day = 1
for i in range(n):
    a_list[i] = deque([int(i) - 1 for i in input().split()])

while (num < n * (n - 1) // 2):
    visit = set([])
    day += 1
    for j in range(n):
        if j not in visit:
            if len(a_list[j]) > 0:
                k = a_list[j][0]
                if a_list[k][0] == j:
                    num += 1
                    visit.add(a_list[j].popleft())
                    visit.add(a_list[k].popleft())
    if ((j == n - 1) & (len(visit) == 0)):
        day = -1
        break
print(day)

Submission status: Wrong Answer

Solution code:
from collections import deque


def main():
    N = int(input())
    A = [deque(map(lambda x: int(x)-1, input().split())) for _ in range(N)]
    ans = 0
    q = deque()
    for i in range(N):
        j = A[i][0]
        if A[j][0] == i:
            A[i].popleft()
            A[j].popleft()
            q.append((i, j))
    ans = 1
    cnt = 0
    used = set()
    while len(q):
        cnt += 1
        i, j = q.popleft()
        if len(A[i]):
            ii = A[i][0]
            if len(A[ii]) and A[ii][0] == i:
                A[i].popleft()
                A[ii].popleft()
                q.append((i, ii))
        if len(A[j]):
            jj = A[j][0]
            if len(A[jj]) and A[jj][0] == j:
                A[j].popleft()
                A[jj].popleft()
                q.append((j, jj))
        if i in used or j in used:
            used = set()
            ans += 1
        used.add(i)
        used.add(j)
    if cnt == N * (N-1)//2:
        print(ans)
    else:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    N = int(input())
    a = [list(map(int, input().split())) for i in range(N)]

    now = [0] * N
    day = 1
    while True:
        nothing = True
        all_finish = True
        check = [False] * N
        for i in range(N):
            if now[i] < N-1:
                all_finish = False
                want = a[i][now[i]] - 1
                if not check[want]:
                    if a[want][now[want]] - 1 == i:
                        now[want] += 1
                        now[i] += 1
                        check[i] = True
                        check[want] = True
                        nothing = False
        if all_finish:
            print(day)
            break
        if nothing:
            print(-1)
            break
        day += 1
    # print(now)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def dec(s):
  n = int(s)
  return n - 1

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

ans = 0
cnt = 0
M = N * (N - 1) // 2
while cnt < M:
  tmp = cnt
  for p in range(N):
    if len(A[p]) == 0:
      continue
    if A[A[p][0]][0] == p: 
      A[A[p][0]].pop(0)
      A[p].pop(0)
      cnt += 1
  if tmp == cnt:
    ans = -2
    break
  else:
    ans += 1
print(ans + 1)

Submission status: Wrong Answer

Solution code:
def topological_sort(E, D):
    D = D[:]
    n = len(E)
    Q = [i for i in range(n) if D[i] == 0]
    L = []
    while Q:
        p = Q.pop()
        L.append(p)
        for vf in E[p]:
            D[vf] -= 1
            if not D[vf]:
                Q.append(vf)
    
    if len(L) != n:
        return False
    return L

N = int(input())

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

Aidx = [None]*N

for i in range(N):
    d = [None]*N
    for j in range(N-1):
        aj = A[i][j]
        d[aj] = j
    Aidx[i] = d[:]

L = N*N
Edge = [[] for _ in range(L)]
Dim = [0]*L

for i in range(N):
    for j in range(i+1, N):
        t = i*N+j
        a = Aidx[i][j]
        if a != N-2:
            ki = A[i][a+1]
            if i > ki:
                ki, li = i, ki
            else:
                li = i
            Edge[t].append(li*N + ki)
            Dim[li*N + ki] += 1
        b = Aidx[j][i]
        if b != N-2:
            kj = A[j][b+1]
            if kj > j:
                kj, j = j, kj
            Edge[t].append(kj*N + j)
            Dim[kj*N + j] += 1

order = topological_sort(Edge, Dim)

if order == False:
    print(-1)
else:
    ans = 1
    used = set()
    for k in order:
        i, j = divmod(k, N)
        if i >= j:
            continue
        if i in used or j in used:
            ans += 1
            used = set([i, j])
        else:
            used.add(i)
            used.add(j)
    print(ans)