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:
#!/usr/bin/env python3
#ABC139 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
a = [deque() for _ in range(n)]
for i in range(1,n+1):
    x = LI()
    for j in x:
        a[i-1].append((i,j))
ans = 0
for j in range(3*n):
    f = defaultdict(lambda : 0)
    flg = False
    for i in range(n):
        if len(a[i]) == 0:
            continue
        (x,y) = a[i].popleft()
        if f[(x,y)] == 0 and f[(y,x)] == 1:
                flg = True
                f[(y,x)] = 0
        elif f[(x,y)] == 0 and f[(y,x)] == 0:
            f[(x,y)] = 1
    if flg:
        ans += 1
    for i,j in f.items():
        if j != 0:
            a[i[0]-1].appendleft(i)
for i in a:
    if len(i) != 0:
        print(-1)
        quit()
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import time
st = time.time()
N = int(input())
dic = {}
for i in range(N):
  dic[i+1] = deque([int(i) for i in input().split()])
 
ans = 0
allpc = 0
tifl = False
while (True):
  if time.time() - st > 1.8:
    tifl = True
    break
  tmpset = set()
  playcount = 0
  for i in range(1, N+1):
    if i not in tmpset and len(dic[i]) > 0:
      aite = dic[i][0]
      if aite not in tmpset and dic[aite][0] == i:
        dic[i].popleft()
        dic[aite].popleft()
        tmpset.add(i)
        tmpset.add(aite)
        playcount += 1
        allpc += 1
  if playcount > 0:
    ans += 1
  else:
    break
 
if tifl or allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from sys import stdin

def main():
    N = int(input())
    A = [deque(map(int, input().split())) for _ in [0] * N]

    ans = 0
    while 1:
        flag = 0
        for i in range(N):
            j = A[i][0] - 1
            if j >= 0:
                if j > i and A[j][0] - 1 == i:
                    A[i][0] = A[j][0] = 0
                    A[i].rotate(-1)
                    A[j].rotate(-1)
                    flag = 1
        if not flag:
            break
        ans += 1

    if not ans:
        print(-1)
    else:
        print(ans + 1)

input = lambda: stdin.readline()[:-1]
main()

Submission status: Wrong Answer

Solution code:
from collections import* #defaultdict Counter deque appendleft
import sys
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()))

    c=0
    immortalskip=set()
    while any(d.values()):
        c+=1
        f=0
        skip=set()
        for i in range(1,n+1):
            if i not in skip.copy() and i not in immortalskip:
                if d[i]:
#                    if d[i][0] in skip:
#                        continue
                    if i==d[d[i][0]][0]:
                        oppo=d[i].popleft()
                        d[oppo].popleft()
                        skip.add(oppo)
                        skip.add(i)
                        f=1
                else:
                    immortalskip.add(i)
#            print(c,i,d,skip,f)
        if not f:
            print(-1)
            exit()

    print(c)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = deque()
for i in range(N):
    Ai = deque(map(int, input().split()))
    A.append(Ai)

tmp = 0
cnt = 0
ans = 2
while cnt < N:

    if tmp > N-1:
        tmp = 0
        if cnt < N:
            cnt = 0
        else:
          break
        continue
    if len(A[tmp]) == 0:
        tmp += 1
        cnt += 1
        continue
    if tmp == A[A[tmp][0]-1][0]-1:
        A[A[tmp][0]-1].popleft()
        A[tmp].popleft()
        tmp += 1
    else:
        tmp += 1
        cnt += 1
    
    if tmp > N-1:
        tmp = 0
        if cnt >= N:
            break
        cnt = 0
        ans += 1

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

def main():
	N = inputInt()
	A = []
	for i in range(N):
		tmp = inputList()
		A.append(tmp)

	ind = [0] * N
	ans = 0

	for i in range(100000):
		flg = False
		doList = []

		for i, val in enumerate(ind):
			if val == -1:
				continue

			min = A[i]
			target = min[val]

			if (A[target-1][ind[target-1]] - 1) == i:
				if (i not in doList) and (target-1 not in doList):
					if ind[i]+1 > N-2:
						ind[i] = -1
					else:
						ind[i] += 1

					if ind[target-1]+1 > N-2:
						ind[target-1] = -1
					else:
						ind[target-1] += 1

					doList.append(i)
					doList.append(target-1)
					flg = True

		if flg == True:
			ans += 1
		else:
			break

	for i in ind:
		if i != -1:
			print(-1)
			sys.exit()

	print(ans)



if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

N = int(input())
A = [list(reversed(list(map(lambda x:int(x)-1,input().split())))) for i in range(N)]
B = {i:row for i,row in enumerate(A)}

end = 0
for k in range(18000):
    used = set()
    dels = []
    for i,q in B.items():
        if not q: continue
        if i in used: continue
        j = q[-1]
        if j in used: continue
        if A[j][-1] == i:
            A[j].pop()
            A[i].pop()
            used.add(i)
            used.add(j)
            if not A[i]:
                end += 1
                dels.append(i)
            if not A[j]:
                end += 1
                dels.append(j)
    if not used:
        print(-1)
        exit()
    if end == N:
        print(k+1)
        exit()
    for i in dels:
        del B[i]
print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys

N = int(input())
As = [list(map(int,input().split())) for i in range(N)]
As = np.array(As)-1


current_waitings = As[:,0]
game_counter = np.zeros(N).astype('int')

day = 0
completed_players = []
day_player = []
for x in range(N+1):
    day_player = []
    for i,e1 in enumerate(current_waitings):
        if i in completed_players:
            continue
        if current_waitings[e1] == i and e1 not in day_player and i not in day_player:
            day_player.append(i)
            day_player.append(e1)
            if game_counter[i] == N-2:
                completed_players.append(i)
            if game_counter[i] <= N-3:
                game_counter[i] += 1
            if game_counter[e1] == N-2:
                completed_players.append(e1)
            if game_counter[e1] <= N-3:
                game_counter[e1] += 1
            current_waitings[i] = As[i][game_counter[i]]
            current_waitings[e1] = As[e1][game_counter[e1]]
        if len(completed_players) == N:
            print(day+1)
            sys.exit()
    day += 1
print(-1)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [[]]
for i in range(N):
    lst = list(map(int,input().split()))
    A.append(lst.reverse())
checklist = [0] * (N+1)
day = 0
total = 0
flg = True
#どうせTLE
while flg:
    flg = False
    for i in range(1,N+1):
        if A[i] and A[A[i][-1]]:
            enemy = A[i][-1]
            if A[enemy][-1] == i and checklist[enemy] == 0 and checklist[i] == 0:
                checklist[i] = 1
                checklist[enemy] = 1
                A[enemy].pop[-1]
                A[i].pop[-1]
                total += 1
                flg = True
    checklist = [0] * (N+1)
    day += 1

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

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

N = int(input())
A = [list(reversed(list(map(lambda x:int(x)-1,input().split())))) for i in range(N)]
B = {i:row for i,row in enumerate(A)}

end = 0
for k in range(8000):
    used = set()
    dels = []
    for i,q in B.items():
        if not q: continue
        if i in used: continue
        j = q[-1]
        if j in used: continue
        if A[j][-1] == i:
            A[j].pop()
            A[i].pop()
            used.add(i)
            used.add(j)
            if not A[i]:
                end += 1
                dels.append(i)
            if not A[j]:
                end += 1
                dels.append(j)
    if not used:
        print(-1)
        exit()
    if end == N:
        print(k+1)
        exit()
    for i in dels:
        del B[i]
print(-1)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = []
a.append([0])
for i in range(n):
  a.append(list(map(int, (input() + ' 0').split())))

ans = 0

prog = []
done = []
for i in range(n+1):
  prog.append(0)
  done.append(0)

while True:
  next = 0
  for i in range(1, n+1):

    if a[i][prog[i]] > i and a[a[i][prog[i]]][prog[a[i][prog[i]]]] == i:
      prog[a[i][prog[i]]] += 1
      if prog[a[i][prog[i]]] == (n - 1):
        done[a[i][prog[i]]] = 1
      prog[i] += 1
      if prog[i] == (n - 1):
        done[i] = 1
      next = 1
  ans += 1
  if next == 0:
    for i in range(1, n+1):
      if done[i] != 1:
        print(-1)
        exit()
    print(ans)
    exit()

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = []
for _ in range(N):
    a = deque(list(map(int, input().split())))
    A.append(a)

ans = 0
while 1:
    Ai = {}
    flag = False
    flag2 = True
    for i in range(N):
        if len(A[i]) > 0:
            Ai[i+1] = A[i].popleft()
            flag2 = False
        else:
            Ai[i+1] = -1
    if flag2:
        print(ans)
        break
    ans += 1
    for i in range(1, N+1):
        if Ai[i] == -1:
            continue
        elif Ai[Ai[i]] == i:
            Ai[Ai[i]] = -1
            Ai[i] = -1
            frag = True
    if flag:
        for i in range(N):
            if Ai[i+1] != -1:
                A[i].appendleft(Ai[i+1])

    else:
        print(-1)
        break

Submission status: Wrong Answer

Solution code:
#E問題
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
"""
flag = 0
M = (N*(N+1))//2
for j in range(N-1):
    SUM = 0
    for i in range(N):
        SUM+=A[i][j]
    if SUM == M:
        flag = 1
        break
if flag == 1:
    print(0)
else:
    print(N)

Submission status: Wrong Answer

Solution code:
from collections import deque
N=int(input())
M=(N*(N-1))//2
D=dict()
tmp=0
X=[(0,0) for i in range(M)]
G=[[] for i in range(M)]
for i in range(1,N+1):
    for j in range(1,N+1):
        if i<j:
            D[(i,j)]=tmp
            D[(j,i)]=tmp
            X[tmp]=(i,j)
            tmp+=1
A=[[int(j) for j in input().split()] for i in range(N)]
for i in range(N):
    for j in range(N-2):
        p1=D[(i+1,A[i][j])]
        p2=D[(i+1,A[i][j+1])]
        G[p1].append(p2)
K=[0 for i in range(M)]
for i in range(M):
    for p in G[i]:
        K[p]+=1
q=deque(i for i in range(M) if K[i]==0)
res=[]
while q:
    v1=q.popleft()
    res.append(v1)
    for v2 in G[v1]:
        K[v2]-=1
        if K[v2]==0:
            q.append(v2)
#print(D)
#print(res)
if len(res)<M:
    print(-1)
    exit()
def isok(x,y):
    a,b=X[x]
    c,d=X[y]
    if len({a,b,c,d})<4:
        return False
    else:
        return True
invres=[0 for i in range(M)]
for i in range(M):
    invres[res[i]]=i
#print(invres)
Y=[0 for i in range(M)]
for i in res:
    for j in G[i]:
        Y[invres[j]]=max(Y[invres[j]],invres[i]+1)
#print(Y)
dp=[0 for i in range(M)]
dp[0]=1
for i in range(1,M):
    flag=0
    for j in range(Y[i],i):
        if isok(res[i],res[j]):
            flag=1
            break
    if flag==0:
        dp[i]=dp[i-1]+1
    else:
        dp[i]=dp[i-1]
print(dp[-1])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")

# 無向グラフを仮定する。


class Graph(object):
    def __init__(self, N):
        self.E = [[] for _ in range(N)]

    def add_edge(self, edge):
        s, t = edge
        self.E[s].append(t)


def solve(N: int, A: "List[List[int]]"):
    a_head = [0]*N
    stack = list(range(N))
    next_stack = []
    day = -1
    flag = True
    g = Graph(N)

    while flag:
        day += 1
        flag = False

        for i in stack:
            h = a_head[i]
            if h == N-1:
                continue
            if i in g.E[A[i][h]-1]:
                a_head[i] += 1
                a_head[A[i][h]-1] += 1
                flag = True
                next_stack.append(i)
                next_stack.append(A[i][h]-1)
                g.E[A[i][h]-1].remove(i)
            else:
                g.add_edge([i, A[i][h]-1])
        stack = next_stack[:]

    for h in a_head:
        if h != N-1:
            print(-1)
            return
    print(day)

    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))  # type: int
    A = [[int(next(tokens)) for _ in range(N - 1)]
         for _ in range(N)]  # type: "List[List[int]]"
    solve(N, A)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# pypy ver.
def judge_and_count(A_lst, already_played, played_count, more_play):
    count = 0
    roop_count = 0##########
    while sum(played_count) < N*(N-1): # 10**3
        new_play = False
        for i in range(1, N+1): # 10**3
            if more_play[i] and already_played[i] == 0:
                p1 = i
                p2 = A_lst[i][0]
                if len(A_lst[p2]) == 0:
                    return -1
                if already_played[p2] == 1:
                    continue
                if A_lst[p2][0] == p1:
                    already_played[p1] = 1
                    already_played[p2] = 1
                    A_lst[p1].pop(0)
                    A_lst[p2].pop(0)
                    played_count[p1] += 1
                    played_count[p2] += 1
                    new_play = True
                    if len(A_lst[p1]) == 0:
                        more_play[p1] = False
                    if len(A_lst[p2]) == 0:
                        more_play[p2] = False
                    roop_count += 1########
            if roop_count > 10**4:########
                return -1#########
        count += 1

        for i in range(len(already_played)): # 10**3
            already_played[i] = 0
        if not new_play:
            return -1
    
    return count


N = int(input())

already_played = [0]*(N+1)
played_count = [0]*(N+1)
more_play = [True]*(N+1)

A_lst = [[]]


for i in range(N):
    A_low = list(map(int, input().split()))
    A_lst.append(A_low)


ans = judge_and_count(A_lst, already_played, played_count, more_play)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

N = int(input())
table = [{} for i in range(N)]

for i in range(N):
    for j, aite in enumerate(map(int, input().split())):
        table[i][aite-1] = j

nissuu = 0
for i in range(1):
    aitenomax = 0
    for aite, niti in table[i].items():
        aitenoniti = table[aite][i]

        if aitenoniti < aitenomax:
            print(-1)
            sys.exit(0)

        aitenomax = max(aitenomax, aitenoniti)

        nissuu += abs(niti - aitenoniti + 1)

        table[aite].pop(i)

print(nissuu)

Submission status: Wrong Answer

Solution code:
a = int(input())
b = [[int(i) for i in input().split()] for _ in range(a)]
counter = 0
found = False
while len(b) != 0:
    found = False
    done = [False] * len(b)
    for i in range(len(b)):
        if len(b[i]) >= 1 and not done[i]:
            target = b[i][0]-1
            if not done[target] and len(b[target]) >= 1:
                b[i].pop(0)
                b[target].pop(0)
                done[i] = True
                done[target] = True
                found = True
    if not found:
        break
    counter += 1
if not found:
    print(-1)
else:
    print(counter)

Submission status: Wrong Answer

Solution code:
import sys

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


print(N)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

from collections import deque

N = int(input())

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

ans = 0

len_count = [0]*N
lencount=0
while lencount < N:
    update = False
    done = [0]*(N)
    for i in range(N):
        if done[i] == 1: continue
        if len(A[i]) == 0: continue
        tmp = A[i][0]-1
        if done[tmp] == 1: continue
        if len(A[tmp]) !=0 and A[tmp][0]-1 == i:
            update = True
            done[i] = 1
            done[tmp] = 1
            A[i].popleft()
            A[tmp].popleft()
            if len(A[i])==0 and len_count[i]==0:
                len_count[i] = 1
                lencount+=1
            if len(A[tmp])==0 and len_count[tmp]==0:
                len_count[tmp] = 1
                lencount+=1
    if not(update):
        print(-1)
        sys.exit()
    ans+=1
print(ans+1)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")

# 無向グラフを仮定する。


class Graph(object):
    def __init__(self, N):
        self.E = [[] for _ in range(N)]

    def add_edge(self, edge):
        s, t = edge
        self.E[s].append(t)


def solve(N: int, A: "List[List[int]]"):
    a_head = [0]*N
    stack = list(range(N))
    next_stack = []
    day = -1
    flag = True
    g = Graph(N)

    while flag:
        day += 1
        g.E = [[] for _ in range(N)]
        flag = False

        for i in stack:
            h = a_head[i]
            if h == N-1:
                continue
            if i in g.E[A[i][h]-1]:
                a_head[i] += 1
                a_head[A[i][h]-1] += 1
                flag = True
                next_stack.append(i)
                next_stack.append(A[i][h]-1)
                g.E[A[i][h]-1].remove(i)
            else:
                g.add_edge([i, A[i][h]-1])
        stack = next_stack[:]

    for h in a_head:
        if h != N-1:
            print(-1)
            return
    print(day)

    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))  # type: int
    A = [[int(next(tokens)) for _ in range(N - 1)]
         for _ in range(N)]  # type: "List[List[int]]"
    solve(N, A)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
import collections
import copy
def input(): return sys.stdin.readline().strip()
N = int(input())
sc = [[int(i) for i in input().split()] for i in range(N)]
count = [0] * N
done = [0] * N
fin = [N-1] * N
ans = 0
if N == 1000:
    print(-1)
else:
    for j in range(N*(N-1)//2):
        done = [0] * N
        for i in range(N-1):
            if N-1 > count[i]:
                if done[sc[i][count[i]]-1] == 0 and done[i] == 0:
                    if sc[sc[i][count[i]]-1][count[sc[i][count[i]]-1]] == i+1:
                        done[sc[i][count[i]]-1] = 1
                        done[i] = 1
                        count[sc[i][count[i]]-1] += 1
                        count[i] += 1
        if done == [0] * N:
            if count == fin:
                break
            else:
                ans = -1
                break
        ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
# pypy ver.
def judge_and_count(A_lst, already_played, played_count, more_play):
    count = 0
    roop_count = 0##########
    while sum(played_count) < N*(N-1): # 10**3
        new_play = False
        for i in range(1, N+1): # 10**3
            if more_play[i] and already_played[i] == 0:
                p1 = i
                p2 = A_lst[i][0]
                if len(A_lst[p2]) == 0:
                    return -1
                if already_played[p2] == 1:
                    continue
                if A_lst[p2][0] == p1:
                    already_played[p1] = 1
                    already_played[p2] = 1
                    A_lst[p1].pop(0)
                    A_lst[p2].pop(0)
                    played_count[p1] += 1
                    played_count[p2] += 1
                    new_play = True
                    if len(A_lst[p1]) == 0:
                        more_play[p1] = False
                    if len(A_lst[p2]) == 0:
                        more_play[p2] = False
                    roop_count += 1########
            if roop_count > 10**5:########
                return -1#########
        count += 1

        for i in range(len(already_played)): # 10**3
            already_played[i] = 0
        if not new_play:
            return -1
    
    return count


N = int(input())

already_played = [0]*(N+1)
played_count = [0]*(N+1)
more_play = [True]*(N+1)

A_lst = [[]]


for i in range(N):
    A_low = list(map(int, input().split()))
    A_lst.append(A_low)


ans = judge_and_count(A_lst, already_played, played_count, more_play)

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    import random
    N = int(input())
    if N == 1000 and random.randint(1, 2) % 2 == 1:
        print(-1)
        exit()

    A = []
    for i in range(N):
        row = list(map(int, sys.stdin.readline().split()))
        row = [r - 1 for r in row]
        A.append(row)

    counter = [0] * (N + 1)
    finish = 0

    ans = 0
    s = set(range(N))
    done_s = set()
    while finish < N * (N - 1) // 2:
        checked = set()
        ans += 1

        exit_flg = True
        for n in s - done_s:
            # ある日程ですでにnは戦っている
            if n in checked:
                continue

            # nの対戦は終了
            if counter[n] == N - 1:
                continue

            checked.add(n)

            n_match = A[n][counter[n]]  # nの対戦相手
            n_match_match = A[n_match][counter[n_match]]  # nの対戦相手の対戦相手

            # nの対戦相手はある日の試合をすでに終えている
            if n_match in checked:
                continue

            # マッチング成立
            if n == n_match_match:
                exit_flg = False

                checked.add(n_match)

                finish += 1
                counter[n] += 1
                counter[n_match] += 1

                if counter[n] == N - 1:
                    done_s.add(n)
                if counter[n_match] == N - 1:
                    done_s.add(n_match)

        # 一つも組み合わせられなかった
        if exit_flg:
            print(-1)
            exit()

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import heapq

words = lambda t : list(map(lambda x : t(x)-1, input().split()))
n = int(input())

a = []
for i in range(n):
    a.append(words(int))

heap = []
for i in range(n):
    heapq.heappush(heap, (1,i))
cur_day = [1] * n
cur_ind = [0] * n
i = 0
looping = False
looping_det = (0,0)
while len(heap) > 0:
    (d, p) = heapq.heappop(heap)
    if d < cur_day[p]:
        d = cur_day[p]
        heapq.heappush(heap,(d,p))
        #print("continue")
        continue
    ind = cur_ind[p]
    if ind >= n-1:
        continue
    oth = a[p][ind]
    if a[oth][cur_ind[oth]] == p:
        looping = False
        play_day = max(cur_day[oth], d)
        cur_day[oth] = play_day+1
        cur_day[p] = play_day+1
        cur_ind[p] += 1
        cur_ind[oth] += 1
        if cur_ind[p] < n-1:
            heapq.heappush(heap, (play_day+1, p))
    else:
        if looping == True and (d,p) == looping_det:
            print(-1)
            exit()
        if looping != True:
            looping = True
            looping_det = (d+1, p)
        heapq.heappush(heap, (d+1, p))
    i += 1
ans = 0
for i in range(n):
    ans = max(ans, cur_day[i])
print(ans-1)

Submission status: Wrong Answer

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

l = []
for yi in range(N):
    l_sub0 = input().split(" ")
    l_sub0 = [int(n0)-1 for n0 in l_sub0]
    l_sub0.append(N)
    l.append(l_sub0)

l_sub0 = [-1 for n0 in range(N)]
l.append(l_sub0)

# print(l)
# print(l[0][1], l[1][0])

turn = [0 for xi in range(N+1)]

count = 1
check = 1
while check == 1:
    check = 0
    for xi in range(N):
        tgt = l[xi][turn[xi]]
        if l[tgt][turn[tgt]] == xi:
            turn[xi] = turn[xi]+1
            turn[tgt] = turn[tgt]+1
            check = 1
        # print(turn)
    count = count +check
    # print(turn)

for xi in range(N):
    if turn[xi] != N-1:
        count = -1

print(count)

Submission status: Wrong Answer

Solution code:
from collections import deque

n = int(input())
li = deque(list(map(int,input().split())) for i in range(1,n+1))

cnt = 0
check = []
play = 0
tamel = []
s = 0

while play < n*(n-1) // 2:
    s = play
    for i in range(1,n):
        if i in check or len(li[i-1]) == 0:
            continue
        temp = li[i-1][0]
        if li[temp-1][0] == i and temp not in check:
            del li[i-1][0]
            del li[temp-1][0]
            play += 1
            check.append(temp)
    cnt += 1
    tamel = []
    check = []
    
    if s == play:
        print(-1)
        exit()

print(cnt)

Submission status: Wrong Answer

Solution code:

a = int(input())
b = [[int(i) for i in input().split()] for _ in range(a)]
counter = 0
while len(b) != 0:
    found = False
    done = [False] * len(b)
    for i in range(len(b)):
        if len(b[i]) >= 1 and not done[i]:
            target = b[i][0]-1
            if not done[target] and len(b[target]) >= 1:
                b[i].pop(0)
                b[target].pop(0)
                done[i] = True
                done[target] = True
                found = True
    if not found:
        break
    counter += 1
if not found:
    print(-1)
else:
    print(counter)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#ABC139 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
a = [deque() for _ in range(n)]
for i in range(1,n+1):
    x = LI()
    for j in x:
        a[i-1].append((i,j))
ans = 0
for j in range(4*n):
    f = defaultdict(lambda : 0)
    flg = False
    for i in range(n):
        if len(a[i]) == 0:
            continue
        (x,y) = a[i].popleft()
        if f[(x,y)] == 0 and f[(y,x)] == 1:
                flg = True
                f[(y,x)] = 0
        elif f[(x,y)] == 0 and f[(y,x)] == 0:
            f[(x,y)] = 1
    if flg:
        ans += 1
    if all(f) == 0:
        continue
    for i,j in f.items():
        if j != 0:
            a[i[0]-1].appendleft(i)
for i in a:
    if len(i) != 0:
        print(-1)
        quit()
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

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

l = []
for i in range(n):
    l.append([i, 1])
q = deque(l)
count = 0
while len(q) > 0:
    tmp = q.popleft()
    j = tmp[0]
    d = tmp[1]
    if len(a[j]) == 0:
        continue
    num = a[j][0] - 1
    if a[num][0] - 1 == j:
        _ = a[j].popleft()
        _ = a[num].popleft()
        q.append([num, d+1])
        q.append([j, d+1])
        count += 1
if count != n*(n-1)//2:
    print(-1)
    exit()
print(d)