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:
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
            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])] if i+1<A[i][j] else D[(A[i][j],i+1)]
        p2=D[(i+1,A[i][j+1])] if i+1<A[i][j+1] else D[(A[i][j+1],i+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:
def main():
    N = int(input())
    a = [list(map(int, input().split())) for i in range(N)]

    now = [0] * N
    day = 0
    gamed_day = [-1] * N
    unfinish_teams = [i for i in range(N)]
    while True:
        had_game = False
        all_finish = True
        for i in unfinish_teams:
            if now[i] < N-1 and gamed_day[i] != day:
                all_finish = False
                want = a[i][now[i]] - 1
                if gamed_day[want] != day:# 今日試合していない
                    if a[want][now[want]] - 1 == i:# 相手の試合相手が自分
                        now[want] += 1
                        now[i] += 1
                        if now[want] >= N-1:
                            unfinish_teams.remove(want)
                        if now[i] >= N-1:
                            unfinish_teams.remove(i)
                        gamed_day[i] = day
                        gamed_day[want] = day
                        had_game = True
                        # print(day+1, i+1, want+1)
        if all_finish:
            if had_game:
                print(day+1)
            else:
                print(day)
            break
        if not had_game:
            print(-1)
            break
        day += 1
    # print(now)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
def solve():
    N = int(input())
    A = []
    for _ in range(N):
        A.append(list(map(int, input().split())))
    I = [0 for _ in range(N)]
    res = 0
    while any(i<N-1 for i in I):
        B = {j:A[j-1][i] for j,i in enumerate(I, start=1) if i<N-1}
        checked = set(j for j in B if B[B[j]] == j)
        print(B)
        if checked:
            for j in checked:
                I[j-1] += 1
            res += 1
        else:
            res = -1
            break
    
    return str(res)

if __name__ == '__main__':
    print(solve())

Submission status: Wrong Answer

Solution code:
N = int(input())

X = N + 1

def to_node(i, j):
	if i < j:
		return i * X + j
	else:
		return j * X + i

def parse_node(node):
	return (node // X, node % X)

a_table = []
v_table = []
r_table = []
for i in range(N):
	for j in range(N):
		v_table.append(set())
		r_table.append(set())

for i in range(N):
	row = [j - 1 for j in map(int, input().strip().split())]
	a_table.append(row)
	prev = to_node(i, row[0])
	for j in range(1, N - 1):
		node = to_node(i, row[j])
		v_table[prev].add(node)
		r_table[node].add(prev)
		prev = node

def t_sort():
	queue = set()
	for i in range(N):
		for j in range(i):
			node = to_node(i, j)
			if len(r_table[node]) == 0:
				queue.add(node)
	queue = [(node, 1) for node in queue]
#	print(queue)
	
	schedule = [set() for i in range(N * N)]
	while queue:
		node, day = queue.pop()
		i, j = parse_node(node)
#		print(i, j)
		while True:
			s = schedule[day]
			day += 1
			if not (i in s or j in s):
				s.add(i)
				s.add(j)
				for next_node in v_table[node]:
					table = r_table[next_node]
					table.remove(node)
					if len(table) == 0:
						queue.append((next_node, day))
				break
	
	for i in range(N):
		for j in range(i):
			node = to_node(i, j)
			if len(r_table[node]) != 0:
				return -1
	
	for i in range(N * N - 1, 0, -1):
		if len(schedule[i]) != 0:
			return i
	
	return -1

#print(a_table)
#for row in v_table:
#	print(list(map(lambda x: (x // X, x % X), row)))

print(t_sort())

Submission status: Wrong Answer

Solution code:

def main():
    
    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 + 500:
        if i % N == 0:
            ans += 1
            flag  = [True] * N #試合をしたかどうかチェック
            i = 0
            
        if check[i] >= N - 1 or 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]: #試合できる時
            check[i] += 1
            check[b - 1] += 1
            flag[i] = False
            flag[b - 1] = False
            tmp = 0
            count += 1
            if count == (N * (N - 1))//2:
                print (ans)
                exit()
        i += 1
        tmp += 1
    
    print (-1)
    return 
            
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():    
    n = int(input())
    a = [list(reversed(list(map(int,input().split())))) for _ in range(n)]
    ans = 0
    c = 0
    while True:
        pop_list = []
        pap = pop_list.append
        for i in range(n):
            for j in range(i+1,n):
                if a[i] and a[j]:
                    if a[i][-1]-1 == j and a[j][-1]-1 == i:
                        pap(i)
                        pap(j)
        if not pop_list:
            ans = -1
            break
        for i in pop_list:
            _ = a[i].pop(-1)
        c += len(pop_list)
        ans += 1
        if c == n:
            break
    print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

N = int(input())
A = [deque(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]
flag = True
ans = 0
while flag:
    flag = False
    tmp = []
    for i in range(N):
        if i in tmp or not len(A[i]):
            continue
        if A[A[i][0]][0] == i:
            tmp.append(i)
            tmp.append(A[i][0])
            A[A[i][0]].popleft()
            A[i].popleft()
            flag = True
    ans += 1

for d in A:
    if len(d):
        print(-1)
        exit()

print(ans)

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
    k = set(range(n))
    while k:
        j = k.pop()
        if len(a[j]) == 0:
            continue
        if f == -1:
            f = 0
        if a[a[j][-1]-1][-1]-1 == j:
            k.discard(a[j][-1]-1)
            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:
n = int(input())


match2rank = dict()
ij2num = dict()
i2queue = [[]]
for i in range(n):
  i2queue.append(list())
  for num in map(int, input().split()):
    i2queue[i].append(num)


cnt = 0
while True:
  used = set()
  for i, q1 in enumerate(i2queue):
    if not q1: continue
    n1 = q1[0]
    if (i2queue[n1 - 1][0] == i + 1):
      used.update([q1.pop(0), i2queue[n1 - 1].pop(0)])
  cnt += 1
  if not used:
    break

for q in i2queue:
  if q:
    print(-1)
    break
else:
  print(cnt)

Submission status: Wrong Answer

Solution code:
n=int(input())
A=[]
for i in range(n):
  A.append([int(i) for i in input().split()])
nn=n*(n-1)//2
F=[[0]*(n+1) for _ in range(n+1)]
cur=0
for i in range(1,n):
  for j in range(i+1,n+1):
    F[i][j]=cur
    F[j][i]=cur
    cur+=1
Edge=[[] for _ in range(nn)]
for i in range(n):
  s=F[i+1][A[i][0]]
  for j in range(1,n-1):
    t=F[i+1][A[i][j]]
    Edge[s].append(t)
    s=t
D=[0]*nn
Chk=[[False]*nn for _ in range(nn)]
loop=False
Stack=[]
for i in range(n):
  s=F[i+1][A[i][0]]
  if D[s]==0:
    Stack.append(s)
    D[s]=1
while Stack:
  s=Stack.pop()
  for g in Edge[s]:
    if D[s]+1>D[g]:
      if Chk[s][g]==True:
        loop=True
        break
      else:
        Stack.append(g)
        D[g]=D[s]+1
        Chk[s][g]=True
print(-1 if loop==True else max(D))

Submission status: Wrong Answer

Solution code:
from collections import deque
import bisect
n=int(input())
data=[deque(map(int,input().split())) 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 len(taisenzumi)!=0 and bisect.bisect_left(taisenzumi,i)==i:continue
		if data[i]:
			aite=data[i][0]
			# print(data[i],aite)
			if len(taisenzumi)!=0 and bisect.bisect_left(taisenzumi,aite-1)==aite-1:continue
			# 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(i)
				taisenzumi.append(aite-1)
				last-=2
				flag=1
			else:continue	
	if not flag:
		break
	
else:
	print(count)
	exit()
print(-1)

Submission status: Wrong Answer

Solution code:
n = int(input())
li = [list(map(int,input().split())) for i in range(1,n+1)]
player = [i 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+1):
        if i in check or len(li[i-1]) == 0:
            continue
        temp = li[i-1][0]
        if li[temp-1][0] == i:
            tamel.append(i-1)
            tamel.append(temp-1)
            play += 1
        check.append(temp)
    cnt += 1
    for i in tamel:
        del li[i][0]
    tamel = []
    check = []
    
    if s == play:
        print(-1)
        exit()

print(cnt)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

N = int(input()) # < 1000

A = [0] * N
s = set()
path = defaultdict(set)
for A in range(1, N+1):
    l = [int(x) for x in input().split()]
    prev = (0, 0)
    for b in l:
        a = A
        if a > b:
            a, b = b, a
        s.add((a, b))
        path[prev].add((a, b))
        prev = a, b
TMP = 1
DONE = 2
L = []
def solve():
    status = {}
    def visit(n):
        if status[n] == TMP:
            raise Exception()
        elif status[n] is None:
            status[n] = TMP
            for m in path[n]:
                visit(m)
            status[n] = DONE
            L.append(n)
            return 1
    for p in s:
        status[p] = None
    for p in s:
        visit(p)
    q = [(0,0)]
   
    D = {(0,0):1}
    while q:
        u = q.pop()
        d = D.get(u, 10e10)
        for v in path[u]:
            alt = d + 1
            if D.get(v, 10e10) > alt:
                D[v] = alt
                q.append(v)
    return D[L[0]]
try:
    print(solve())
except:
    print(-1)

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
    klist=[]
    #print()
    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:
                if not(i in klist):
                    klist.append(i)
                    klist.append(alist[i][nowlist[i]]-1)
                    nextlist[alist[i][nowlist[i]]-1]=-1
                    nextlist[i]=-1
                    nowlist[alist[i][nowlist[i]]-1]+=1
                    nowlist[i]+=1
                    incre+=2
                    swit=1
            #print(nextlist, nowlist)
    day+=1
    #print('now:', nowlist)
    #print(nextlist)
    if swit==0:
        day=-1
        error=1

print(day)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

now = []
for i in range(n):
    now.append(a[i].popleft()-1)
    a[i].append(0)
    a[i].append(0)
# print(a)
# print(now)

ans = 0
battle = 0
max_battle = n*(n-1)//2
while battle < max_battle:
    checked = [False]*n
    nogame = True
    for i in range(n):
        if checked[i] or checked[now[i]] or now[i]==-1:
            continue
        checked[i] = True
        checked[now[i]] = True
        if now[now[i]]==i:
            x = i
            y = now[i]
            now[x] = a[x].popleft()-1
            now[y] = a[y].popleft()-1
            battle += 1
            nogame = False

    if nogame:
        print(-1)
        exit()
    else:
        ans += 1

print(ans)

Submission status: Wrong Answer

Solution code:
import sys, time

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.6:
		print(-1)
		sys.exit()
	day += 1
print(day)

Submission status: Wrong Answer

Solution code:
def solve():
  import sys
  import math

  sys.setrecursionlimit(10**7)
  readline = sys.stdin.readline

  
  n = int(readline())
  a = [list(map(int,readline().split())) for _ in range(n)]
  c = [0]*n
  d = 0
  m = (n-1)*n
  
  while sum(c) < m:
    candidate = []
    for i in range(n):
      if i in candidate or c[i] > n-2:
        continue
      j = a[i][c[i]]-1
      if a[j][c[j]]-1 == i:
        c[i] += 1
        c[j] += 1
        candidate += [i]
        candidate += [j]
    if candidate:
      d+=1
    else:
      print(-1)
      quit()
      
  print(d)


if __name__ == '__main__':
  solve()

Submission status: Wrong Answer

Solution code:
from collections import* #defaultdict Counter deque appendleft

 
def main():
    n=int(input())
    d=defaultdict(deque)
    for i in range(n):
        d[i+1]=deque(map(int,input().split()))

    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]:
                    if d[i][0] in skip:
                        continue
                    else:
                        oppo=d[i].popleft()
                        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:
import sys

def solve():
    input = sys.stdin.readline
    N = int(input())
    A = [[int(a) - 1 for a in input().split()] for _ in range(N)]

    #print(A)
    day = 1
    match = [0 for i in range(N)]

    #print(match)
    while True:
        onmatch = set()
        for i in range(N):
            if i not in onmatch and match[i] < N - 1:
                vs = A[i][match[i]]
                if match[vs] < N - 1:
                    if A[vs][match[vs]] == i and vs not in onmatch:
                        onmatch |= {vs}
                        match[i] += 1
                        match[vs] += 1
        if onmatch: day += 1
        else: break
    #print(match)

    for i in match[:N]:
        if i < N - 1:
            print(-1)
            break
    else: print(day)

    return 0

if __name__ == "__main__": solve()

Submission status: Wrong Answer

Solution code:
import math
import copy
from operator import mul
from functools import reduce
from collections import defaultdict
from collections import Counter
from collections import deque
# 直積 A={a, b, c}, B={d, e}:のとき，A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)}: product(A, B)
from itertools import product
# 階乗 P!: permutations(seq), 順列 {}_len(seq) P_n: permutations(seq, n)
from itertools import permutations
# 組み合わせ {}_len(seq) C_n: combinations(seq, n)
from itertools import combinations
# 一次元累積和
from itertools import accumulate
from bisect import bisect_left, bisect_right
from heapq import heappush, heappop

import re
# import numpy as np
# from scipy.misc import comb

# 再帰がやばいとき
import sys
sys.setrecursionlimit(10**9)

def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W

# 四方向: 右, 下, 左, 上
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]
 
def i_inpl(): return int(input())
def l_inpl(): return list(map(int, input().split()))
def line_inpl(x): return [i_inpl() for _ in range(x)]

INF = int(1e30)
MOD = int(1e9)+7 # 10^9 + 7

# field[H][W]
def create_grid(H, W, value = 0):
    return [[ value for _ in range(W)] for _ in range(H)]

########

def main():
    N = i_inpl()
    f = []
    for _ in range(N):
        fi = l_inpl()
        f.append(fi)
    tmp = set()
    ans = 0
    for i in range(N-1):
        flag = False
        ttmp = set()
        for j in range(N):
            if "{}{}".format(f[j][i], j+1) in tmp:
                tmp.remove("{}{}".format(f[j][i], j+1))
                if len(ttmp) == 0 or (j+1) in ttmp or f[j][i] in ttmp:
                    ans += 1
                ttmp.add(j+1)
                ttmp.add(f[j][i])
                flag = True
            else:
                tmp.add("{}{}".format(j+1, f[j][i]))
        if not flag:
            print(-1)
            return
    if len(tmp) == 0:
        print(ans)
    else:
        print(-1)
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
r=[]
a=[]
b=[]
for i in range(n):
  r.append([int(i) for i in input().split()])
for i in range(n):
  k=[]
  f=[]
  for j in range(n):
    if len(r[j])!=0:
      p=r[j][0]-1
      if r[p][0]==j+1:
        if j+1 not in f:
          if p+1 not in f:
            k.append([r[j].pop(0),r[p].pop(0)])
            f.append(j+1)
            f.append(p+1)
  if len(k)==0:
    break
  else:
    for o in k:
      a.append(o)
    b.append(k)
if len(a)==(n*(n-1)//2):
  print(len(b))
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.6:
		print(-1)
		sys.exit()
	day += 1
print(day)

Submission status: Wrong Answer

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

ans=0
cnt=0
for j in range(n*n//2+1):
    f=0
    q=[0]*n
    for i in range(n):        
        if len(a[i])>0 and len(a[a[i][0]-1])>0 and i+1==a[a[i][0]-1][0] and i<a[i][0]-1 and q[a[i][0]-1]==0:
            q[a[i][0]-1]+=1
            a[a[i][0]-1].pop(0)
            a[i].pop(0)
            
            #q.append(i)
            #q.append(a[i][0]-1)
            f+=1    
            cnt+=1
    #if len(q)>0:
        #for k in q:
            #a[k].pop(0)
            
            
    if f==0 and cnt<n*(n-1)//2:
        print(-1)
        exit()
    elif f>0:
        ans+=1
    else:
        print(ans)
        exit()

Submission status: Wrong Answer

Solution code:
from collections import deque

n = int(input())
a = ["dummy!"] + [list(map(int, input().split())) for _ in range(n)]
t = 0
f = 1
cur = [0]*(n+1)
date = [0]*(n+1)
seed = deque()
for i in range(1,n+1):
    op = a[i][cur[i]]
    if a[op][cur[op]] == i:
        seed.append((i,op))
        cur[i] += 1
        cur[op] += 1
        date[i] = date[op] = max(date[i],date[op]) + 1
print(seed)
while seed:
    p,q = seed.popleft()   
    for i in p,q:
        if cur[i] >= n-1:
            continue
        op = a[i][cur[i]]
        if a[op][cur[op]] == i:
            seed.append((i,op))
            cur[i] += 1
            cur[op] += 1
            date[i] = date[op] = max(date[i],date[op]) + 1
if any(x < n-1 for x in cur[1:]):
    print(-1)
else:
    print(max(date))

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 = max(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:
# 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()
    A[i].reverse()
    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:
n=int(input())
r=[]
a=[]
b=[]
for i in range(n):
  r.append([int(i) for i in input().split()])
for i in range(n):
  k=[]
  f=[]
  for j in range(n):
    if len(r[j])!=0:
      p=r[j][0]-1
      if r[p][0]==j+1:
        if j+1 not in f:
          if p+1 not in f:
            k.append([r[j].pop(0),r[p].pop(0)])
            f.append(j+1)
            f.append(p+1)
  if len(k)==0:
    break
  else:
    for o in k:
      a.append(o)
    b.append(k)
if len(a)==(n*(n-1)//2):
  print(len(b))
else:
  print(-1)

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):
        q.append(i)
    ans = 1
    cnt = 0
    used = set()
    while len(q):
        i = q.popleft()
        if len(A[i]) == 0:
            continue
        j = A[i][0]
        if len(A[j]) and A[j][0] == i:
            cnt += 1
            if i in used or j in used:
                used = set()
                ans += 1
            used.add(i)
            used.add(j)
            A[i].popleft()
            A[j].popleft()
            q.append(i)
            q.append(j)
    if cnt == N * (N-1)//2:
        print(ans)
    else:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import* #defaultdict Counter deque appendleft

 
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:
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
                            bb = True
                        else:
                            ls[i] = -1
                            bbb += 1
                            
                        if ls[mt[i]-1] + 1 < n - 1:
                            ls[mt[i]-1] += 1
                            bb = True
                        else:
                            ls[mt[i]-1] = -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:
import sys
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
count=0
check=[-1,0]
while count!=n*(n-1)//2 and day<=10**4:
  if check[len(check)-2]==check[len(check)-1]:
    print(-1)
    sys.exit()
  L=[0 for i in range(n)]
  f1=0
  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
        count+=1
  day+=1
  check.append(count)
if day>10**4:
  print(-1)
  sys.exit()
print(day)

Submission status: Wrong Answer

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

a_i = [0] * n

day = 0
while True:
    matches = []
    has_match = False
    a_end = 0
    for i in range(n):
        if a_i[i] == n - 1:
            a_end += 1
            continue
        match = {i+1, a[i][a_i[i]]}
        if match in matches:
            lst = list(match)
            a_i[lst[0] - 1] += 1
            a_i[lst[1] - 1] += 1
            has_match = True
        else:
            matches.append(match)
    if has_match:
        day += 1
        if a_end == n:
            break
    else:
        day = -1
        break

print(day)