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: Runtime Error

Solution code:
n = int(input())
import collections
plan = {}
for i in range(n):
    plan[i+1] = collections.deque(list(map(int, input().split())))

remain, updated = [player for player in range(1,n+1)],[player for player in range(1,n+1)]
cnt = 0

while remain != []:
    visit = [p for p in remain]
    flag = True
    nex_update = []
    while remain != [] and updated != []:
        p_check = updated.pop()
        visit.remove(p_check)
        if plan[p_check][0] in visit and plan[plan[p_check][0]][0] == p_check:
            visit.remove(plan[p_check][0])
            if plan[p_check][0] in updated: updated.remove(plan[p_check][0])
            nex_update.append(plan[plan[p_check][0]].popleft())
            if len(plan[plan[p_check][0]]) == 0: remain.remove(plan[p_check][0])
            nex_update.append(plan[p_check].popleft())
            if len(plan[p_check]) == 0: remain.remove(p_check)
            flag = False 
    if flag:
        cnt = -1
        break
    updated = nex_update
    cnt += 1
print(cnt)

Submission status: Runtime Error

Solution code:
a = [None] + [list(map(int, input().split())) for _ in range(n)]
k = 0
l = n * (n - 1)
while(l):
    v = [i for i in range(1, n + 1) if a[i] and a[a[i][-1]] and
         a[a[i][-1]][-1] == i]
    if not v:
        k = -1
        break
    for i, j in v:
        a[i].pop()
        a[j].pop()
    k += 1
    l -= len(v)
print(k)

Submission status: Runtime Error

Solution code:
a = [None] + [list(map(int, input().split())) for _ in range(n)]
k = 0
l = n * (n - 1)
while(l):
    v = [i for i in range(1, n + 1) if a[i] and a[i][-1] > i
         and a[a[i][-1]] and a[a[i][-1]][-1] == i]
    if not v:
        k = -1
        break
    for i, j in v:
        a[i].pop()
        a[j].pop()
    k += 1
    l -= len(v)
print(k)

Submission status: Runtime Error

Solution code:
N = int(input())
A = []
for i in range(N):
	A.append(list(map(int, input().split())))
days = 0
l = [0]*N
for _ in range(N(N-1)//2):
	done = 0
	for i in range(N):
		if l[i] == 0:
			if len(A[i]):
				l[i] = A[i].pop(0)
			else:
				l[i] = 0
 
	if not sum(l): break
 
	for i in range(N):
		if l[l[i]-1] == i+1 and l[i] and l[l[i]-1]:
			l[l[i]-1] = 0
			l[i] = 0
			done = 1
	
	if done:
		days += 1
	else:
		print(-1)
		exit()
print(days)

Submission status: Runtime Error

Solution code:
n=int(input())
a=[[int(x)-1 for x in input().split()] for _ in range(n)]

cnt=0
id=[[0]*n for _ in range(n)]
for i in range(n):
	for j in range(i+1,n):
		id[i][j] = cnt
		cnt+=1
def toid(x,y):
	return id[x][y] if x<y else id[y][x]

for i in range(n):
	for j in range(n-1):
		a[i][j] = toid(i,a[i][j])

nedge = n*(n-1)//2
g=[[]for _ in range(nedge)+5]

for i in range(n):
	for j in range(1,n-1):
		g[a[i][j-1]].append(a[i][j])

calced=[False]*(nedge+5)
visited=[False]*(nedge+5)
dp=[0]*nedge

def dfs(v):
	if visited[v]:
		if not calced[v]:
			return -1
		return dp[v]
	
	visited[v]=True
	dp[v]=1
	for u in g[v]:
		ret = dfs(u)
		if ret == -1:
			return -1
		dp[v] = max(dp[v],ret+1)
	
	calced[v]=True
	return dp[v]

ans = 0
for i in range(nedge):
	res = dfs(i)
	if res==-1:
		print(-1)
		exit()
	ans = max(ans,res)
print(ans)

Submission status: Runtime Error

Solution code:
n=int(input())
a=[[int(x)-1 for x in input().split()] for _ in range(n)]

cnt=0
id=[[0]*n for _ in range(n)]
for i in range(n):
	for j in range(i+1,n):
		id[i][j] = cnt
		cnt+=1
def toid(x,y):
	return id[x][y] if x<y else id[y][x]

for i in range(n):
	for j in range(n-1):
		a[i][j] = toid(i,a[i][j])

nedge = n*(n-1)//2
g=[[]for _ in range(nedge)]

for i in range(n):
	for j in range(1,n-1):
		g[a[i][j-1]].append(a[i][j])

calced=[False]*nedge
visited=[False]*nedge
dp=[0]*nedge

def dfs(v):
	if visited[v]:
		if not calced[v]:
			return -1
		return dp[v]
	
	visited[v]=True
	dp[v]=1
	for u in g[v]:
		ret = dfs(u)
		if ret == -1:
			return -1
		dp[v] = max(dp[v],ret+1)
	
	calced[v]=True
	return dp[v]

ans = 0
for i in range(nedge):
	res = dfs(i)
	if res==-1:
		print(-1)
		exit()
	ans = max(ans,res)
print(ans)

Submission status: Runtime Error

Solution code:
a = [None] + [list(map(int, input().split())) for _ in range(n)]
k = 0
l = n * (n - 1) // 2
while(l):
    v = [(i, a[i][-1]) for i in range(1, n) if a[i] and a[i][-1] > i
         and a[a[i][-1]] and a[a[i][-1]][-1] == i]
    if not v:
        k = -1
        break
    for i, j in v:
        a[i].pop()
        a[j].pop()
    k += 1
    l -= len(v)
print(k)

Submission status: Runtime Error

Solution code:
from collections import deque
n=int(input())
a=[list(map(lambda x:int(x)-1,input().split())) for _ in range(n)]
g = [[[] for _ in range(n)] for _ in range(n)]
h=[[0]*n for _ in range(n)]
for i in range(n):
	for j in range(1,n-1):
		maf = max(i,a[i][j-1])
		mif = min(i,a[i][j-1])
		mat = max(i,a[i][j])
		mit = min(i,a[i][j])
		g[mif][maf].append([mit,mat])
		h[mit][mat] += 1

st = deque([])
sj = deque([])
for i in range(n):
	for j in range(i+1,n):
		if h[i][j]==0:
			st.append([i,j])
			sj.append([i,j])
ans=[]
while(st):
	f = st.popleft()
	ans.append(f)
	for mi,ma in g[f[0]][f[1]]:
		h[mi][ma]-=1
		if h[mi][ma] == 0:
			st.append([mi,ma])

if len(ans)!=n*(n-1)//2:
	print(-1)
	exit()

dp = [[0]*n for _ in range(n)]
def dfs(x,y):
	if dp[x][y]:
		return dp[x][y]
	if g[x][y]==[]:
		dp[x][y]=1
		return dp[x][y]
	for e in g[x][y]:
		dp[x][y] = max(dfs(e[0],e[1])+1,dp[x][y])
	return dp[x][y]
maxx = 0
for edge in sj:
	maxx = max(maxx,dfs(edge[0],edge[1]))
print(maxx)

Submission status: Runtime Error

Solution code:
n = int(input())
a = [None] + [list(map(int, input().split())) for _ in range(n)]
k = 0
l = n * (n - 1) // 2
while(l):
    v = [(i, a[i][-1]) for i in range(1, n + 1) if a[i][-1] and a[i][-1] < i
         and a[a[i][-1]] and a[a[i][-1]][-1] == i]
    if not v:
        k = -1
        break
    for i, j in v:
        a[i].pop()
        a[j].pop()
    k += 1
    l -= len(v)
print(k)

Submission status: Runtime Error

Solution code:
n=int(input());l=[list(map(int,input().split()))for i in[0]*n];a=[0]*n;d=1;k=n*(n-1)
while sum(a)<k and 0<d<9999:
 L=[0]*n;y=0;d+=1
 for i in range(n):
  if a[i]<n-1:
   x=l[i][a[i]]-1
   if l[x][a[x]]-1==i+L[x]+L[i]:
    a[i]+=1;a[x]+=1;L[i]=L[x]=y=1
 d*=y
print([k//2,d-1][d<9999])

Submission status: Runtime Error

Solution code:
import sys
from math import atan2, cos, pi

import numpy as np


def check(engines, theta):
    x, y = 0, 0
    cur = 0
    best = 0
    for dx, dy in engines:
        nx = x + dx
        ny = y + dy
        r = (nx ** 2 + ny ** 2) ** 0.5
        new = r * cos(atan2(ny, nx) - theta)

        if cur < new:
            x, y = nx, ny
            cur = new
            best = r
    return best


n = int(input())
engines = []
for line in sys.stdin:
    x, y = map(int, line.split())
    engines.append((x, y))

ans = 0
for dx, dy in engines:
    ans = max(ans, check(engines, atan2(dy, dx)))
print(ans)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
n = int(input())
a = [deque(map(lambda x:int(x) - 1, input().split())) for _ in range(n)]
q = deque()
pre_q = deque()
day = 0


def check(p, q):
    if not len(a[p]) == 0:
        o = a[p][0]
        if a[o][0] == p:
            if p < o and not (p, o) in q:
                q.append((p, o))
            elif not (o, p) in q:
                q.append((o, p))

for p in range(n):
    check(p, q)

while len(q) > 0:
    day += 1
    pre_q = q.copy()
    q.clear()
    for (p, o) in pre_q:
        a[p].popleft()
        a[o].popleft()
        check(p, q)
        check(o, q)


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

print(day)

Submission status: Runtime Error

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

total=0
n=[0 for _ in l]
c=[False for _ in range(N)]
end=[False for _ in range(N)]
while sum(n)<N*(N-1):
    total+=1
    check=[False for _ in range(N)]
    #print("n:",total)
    flag=True
    for j in range(N):
        #print("j:{}".format(j))
        if end[j] or check[j]:
            continue
        tmp=l[j][n[j]]-1
        if  check[tmp]:
            continue
        if j==l[tmp][n[tmp]]-1:
            flag=False
            n[j]+=1
            n[tmp]+=1
            check[j]=True
            check[tmp]=True
            """
            if n[j]==N-1:
                end[j]=True
            if n[tmp]==N-1:
                end[tmp]=True
            """
    if flag:
        print(-1)
        exit()
print(total)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
n = int(input())
a = [deque(map(lambda x:int(x) - 1, input().split())) for _ in range(n)]
q = deque()
pre_q = deque()
day = 0


def check(p, q):
    if len(a[p]) == 0: return 0
    o = a[p][0]
    if a[o][0] == p:
        if p < o and not (p, o) in q:
            q.append((p, o))
        elif not (o, p) in q:
            q.append((o, p))

for p in range(n):
    check(p, q)

while len(q) > 0:
    day += 1
    pre_q = q.copy()
    q.clear()
    for (p, o) in pre_q:
        a[p].popleft()
        a[o].popleft()
        check(p, q)
        check(o, q)


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

print(day)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
n = int(input())
a = [deque(map(lambda x:int(x) - 1, input().split())) for _ in range(n)]
q = deque()
pre_q = deque()
day = 0


def check(p, q):
    if len(a[p]) == 0: return
    o = a[p][0]
    if a[o][0] == p:
        if p < o and not (p, o) in q:
            q.append((p, o))
        elif not (o, p) in q:
            q.append((o, p))

for p in range(n):
    check(p, q)

while len(q) > 0:
    day += 1
    pre_q = q.copy()
    q.clear()
    for (p, o) in pre_q:
        a[p].popleft()
        a[o].popleft()
        check(p, q)
        check(o, q)


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

print(day)

Submission status: Runtime Error

Solution code:
import sys, collections
n = int(input())
a = [collections.deque(map(lambda x:int(x) - 1, input().split())) for _ in range(n)]
q = collections.deque()
pre_q = collections.deque()
day = 0


def check(p, q):
    if len(a[p]) == 0: return
    o = a[p][0]
    if a[o][0] == p:
        if p < o and not (p, o) in q:
            q.append((p, o))
        elif not (o, p) in q:
            q.append((o, p))

for p in range(n):
    check(p, q)

while len(q) > 0:
    day += 1
    pre_q = q.copy()
    q.clear()
    for (p, o) in pre_q:
        a[p].popleft()
        a[o].popleft()
        check(p, q)
        check(o, q)


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

print(day)

Submission status: Runtime Error

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

c=[False for i in range(N)]
total=0
n=[0 for _ in l]
end=[False for _ in range(N)]
while sum(n)<N*(N-1):
    total+=1
    check=c.copy()
    flag=True
    for j in range(N):
        #print("j:{}".format(j))
        if end[j] or check[j]:
            continue
        tmp=l[j][n[j]]-1
        if  check[tmp]:
            continue
        if j==l[tmp][n[tmp]]-1:
            flag=False
            n[j]+=1
            n[tmp]+=1
            check[j]=True
            check[tmp]=True
            if n[j]==N-1:
                end[j]=True
            if n[tmp]==N-1:
                end[tmp]=True
    if flag:
        print(-1)
        exit()
print(total)

Submission status: Runtime Error

Solution code:
import collections as cl
def l(): #intのlist
    return list(map(int,input().split()))
def onem(): #Nとかの取得
    return int(input())
n = onem()

on = []
de = cl.deque()
for i in range(n):
    k = l()
    for j in range(n-1):
        k[j] -= 1
    k.reverse()
    de.append([k[0],i])
    on.append(cl.deque(k))


co = 1
ddd = cl.deque()
de.append([-1,-1])
opo = [1 for i in range(n)]
cl = opo
while de:
    kkk = de.popleft()
    if kkk[0] == -1 and kkk[1] == -1:
        if sum(cl) == n:
            co = -1
            break
        if len(de) == 0:
            break
        de.append([-1,-1])
        co += 1
        cl = opo

    elif ppp[kkk[0]] != 0 and on[kkk[0]][0] == kkk[1] and cl[kkk[0]] and cl[kkk[1]]:
        cl[kkk[0]] = 0
        cl[kkk[1]] = 0
        on[kkk[0]].popleft()
        on[kkk[1]].popleft()
        ppp[kkk[0]] -= 1
        ppp[kkk[1]] -= 1
        if ppp[kkk[1]] != 0 != 0 and ppp[kkk[0]] != 0 and on[kkk[1]][0] == kkk[0] and on[kkk[0]][0] == kkk[1]:
            de.append([on[kkk[1]][0],kkk[1]])
        else:
            if len(on[kkk[1]]) != 0:
                de.append([on[kkk[1]][0],kkk[1]])
            if len(on[kkk[0]]) != 0:
                de.append([on[kkk[0]][0],kkk[0]])


print(co)

Submission status: Runtime Error

Solution code:
n = int(input())
table = []
for i in range(n):
  a = list(map(int, input().split()))
  table.append(a)
cursor = [0]*(n+1)
is_matched = [False] * (n+1)
d = 0
match = 0
while match < n * (n-1) //2:
  for i in range(1, n+1):
    for j in range(i+1, n+1):
      if table[i][cursor[i]] == j and not is_matched[i] and table[j][cursor[j]] == i and not is_matched[j]:
        match += 1
        cursor[i] += 1 
        is_matched[i] = True
        cursor[j] += 1
        is_matched[j] = True
      
  d += 1
  is_matched =  [False] * (n+1)
print(d)

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(input().split()))

Submission status: Runtime Error

Solution code:
N = int(input())
A = []
for i in range(N):
	l = list(map(int,input().split()))
	A.append([i-1 for i in l])
match_num = [0 for i in range(N)]
match_dict = {}
idx = 0
for i in range(N-1):
	for j in range(i+1, N):
		match_dict[(i,j)] = idx
		idx += 1
M = idx
edge = [[] for i in range(M)]
parent = [[] for i in range(M)]
for i in range(N):
	for j in range(N-2):
		a = A[i][j]
		a_nxt = A[i][j+1]
		x,y = min(i,a), max(i,a)
		z,w = min(i,a_nxt), max(i,a_nxt)
		m1 = match_dict[(x,y)]
		m2 = match_dict[(z,w)]
		edge[m1].append(m2)
		parent[m2].append(m1)
finish = [False for i in range(M)]
candidate = [i for i in range(M) if len(parent[i]) == 0]
depth = [-1 for i in range(M)]


day = 0
while len(candidate) > 0:0
	new_candidate = []
	for c in candidate:
		finish[c] = True
		for e in edge[c]:
			parent[e].remove(c)
			if len(parent[e]) == 0:
				new_candidate.append(e)
		edge[c] = []
	candidate = new_candidate
	day += 1
print(day if all(finish) else -1)

Submission status: Runtime Error

Solution code:
import os
import sys
from collections import defaultdict
from functools import lru_cache

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

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

# グラフつくる
nodes = set()
sources = set()
graph = defaultdict(list)
ins = defaultdict(int)
for i in range(N):
    for j in range(N - 2):
        a, b = i, A[i][j] - 1
        a, b = min(a, b), max(a, b)
        c, d = i, A[i][j + 1] - 1
        c, d = min(c, d), max(c, d)

        graph[a * N + b].append(c * N + d)
        ins[c * N + d] += 1
        sources.add(a * N + b)

        nodes.add(a * N + b)
        nodes.add(c * N + d)

assert False

# トポロジカルソート
S = []
for v in sources:
    if ins[v] == 0:
        S.append(v)
L = []
while S:
    v = S.pop()
    L.append(v)
    for u in graph[v]:
        ins[u] -= 1
        if ins[u] == 0:
            S.append(u)
if len(L) != len(nodes):
    print(-1)
    exit()

seen = []


@lru_cache(maxsize=None)
def dfs(v):
    ret = 0
    for u in graph[v]:
        ret = max(ret, dfs(u))
    return ret + 1


ans = 0
for v in sources:
    ans = max(ans, dfs(v))
print(ans)

Submission status: Runtime Error

Solution code:
import os
import sys
from collections import defaultdict
from functools import lru_cache

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

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

# グラフつくる
nodes = set()
sources = set()
graph = defaultdict(list)
ins = defaultdict(int)
for i in range(N):
    for j in range(N - 2):
        a, b = i, A[i][j] - 1
        a, b = min(a, b), max(a, b)
        c, d = i, A[i][j + 1] - 1
        c, d = min(c, d), max(c, d)

        graph[a * N + b].append(c * N + d)
        ins[c * N + d] += 1
        sources.add(a * N + b)

        nodes.add(a * N + b)
        nodes.add(c * N + d)

# トポロジカルソート
S = []
for v in sources:
    if ins[v] == 0:
        S.append(v)
L = []
while S:
    v = S.pop()
    L.append(v)
    for u in graph[v]:
        ins[u] -= 1
        if ins[u] == 0:
            S.append(u)

if len(L) != len(nodes):
    print(-1)
    exit()

seen = []


@lru_cache(maxsize=None)
def dfs(v):
    ret = 0
    for u in graph[v]:
        ret = max(ret, dfs(u))
    return ret + 1

assert False

ans = 0
for v in sources:
    ans = max(ans, dfs(v))
print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())
matches = [[int(v) - 1 for v in input().split()] for _ in range(n)]

class Node:
    def __init__(self, pl1, pl2):
        self.pl1 = pl1
        self.pl2 = pl2
        self.next = []
    
    def __str__(self):
        return f"({self.pl1}, {self.pl2})"

def swap(s, t):
    if s < t:
        return s, t
    else:
        return t, s

table = {}
for p in range(n):
    for q in range(p+1, n):
        table[p, q] = Node(p, q)

starts = set()
for player in range(n):
    before = table[swap(player, matches[player][0])]
    starts.add(before)
    for opponent in matches[player][1:]:
        nex = table[swap(player, opponent)]
        before.next.append(nex)
        before = nex


def dfs(start, depth=1, used=set()):
    stack = []
    used = set()
    stack.append(start)
    used.add(start)
    res = -1
    while len(stack) > 0:
        node = stack.pop()
        if len(node.next) == 0:
            res = max(res, len(used))
        else:
            for nx in node.next:
                if nx not in used:
                    used.add(nx)
                    stack.append(nx)
                    break
    return res

result = 0
for start in starts:
    temp = dfs(start)
    if temp < 0:
        result = -1
        break
    result = max(result, temp)

print(result)

Submission status: Runtime Error

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
stflag = False
while (True):
  if ime.time() -st > 1.9:
    stflag = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[i].appendleft(aite)
          dic[aite].appendleft(aiteaite)
      else:
        dic[i].appendleft(aite)
 
  if playcount > 0:
    ans += 1
  else:
    break
if stflag:
  print(int(N * (N-1))//2)
if allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
import time
N = int(input())
dic = {}
for i in range(N):
  dic[i+1] = deque([int(i) for i in input().split()])
st = time.time()
 
ans = 0
allpc = 0
stflag = False
while (True):
  if st -time.time() > 1.9:
    stflag = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[i].appendleft(aite)
          dic[aite].appendleft(aiteaite)
      else:
        dic[i].appendleft(aite)
 
  if playcount > 0:
    ans += 1
  else:
    break
if stflag:
  print(int(N * (N-1))//2)
if allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)
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
stflag = False
while (True):
  if st -time.time() > 1.9:
    stflag = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[i].appendleft(aite)
          dic[aite].appendleft(aiteaite)
      else:
        dic[i].appendleft(aite)
 
  if playcount > 0:
    ans += 1
  else:
    break
if stflag:
  print(int(N * (N-1))//2)
if allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)

Submission status: Runtime Error

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
stflag = False
while (True):
  if st -time.time() > 1.9:
    stflag = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[i].appendleft(aite)
          dic[aite].appendleft(aiteaite)
      else:
        dic[i].appendleft(aite)
 
  if playcount > 0:
    ans += 1
  else:
    break
if stflag:
  print(int(N * (N-1))//2)
if allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)
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
stflag = False
while (True):
  if st -time.time() > 1.9:
    stflag = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[i].appendleft(aite)
          dic[aite].appendleft(aiteaite)
      else:
        dic[i].appendleft(aite)
 
  if playcount > 0:
    ans += 1
  else:
    break
if stflag:
  print(N * (N-1) // 2)
elif allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)

Submission status: Runtime Error

Solution code:
import sys

n = int(input())
matches = [[int(v) - 1 for v in input().split()] for _ in range(n)]

sys.setrecursionlimit((n ** 2) * 2)

class Node:
    def __init__(self, pl1, pl2):
        self.pl1 = pl1
        self.pl2 = pl2
        self.next = []
    
    def __str__(self):
        return f"({self.pl1}, {self.pl2})"

def swap(s, t):
    if s < t:
        return s, t
    else:
        return t, s

table = {}
for p in range(n):
    for q in range(p+1, n):
        table[p, q] = Node(p, q)

starts = set()
for player in range(n):
    before = table[swap(player, matches[player][0])]
    starts.add(before)
    for opponent in matches[player][1:]:
        nex = table[swap(player, opponent)]
        before.next.append(nex)
        before = nex


def dfs(start, depth=1, used=set()):
    if start in used:
        return -1
    elif len(start.next) == 0:
        return depth
    else:
        used = set(used)
        used.add(start)
        return max([dfs(nx, depth + 1, used) for nx in start.next])

result = 0
for start in starts:
    temp = dfs(start)
    if temp < 0:
        result = -1
        break
    result = max(result, temp)

print(result)

Submission status: Runtime Error

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
stflag = False
while (True):
  if st -time.time() > 1.9:
    stflag = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[i].appendleft(aite)
          dic[aite].appendleft(aiteaite)
      else:
        dic[i].appendleft(aite)
 
  if playcount > 0:
    ans += 1
  else:
    break
if stflag:
  print(int(N * (N-1))//2)
if allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)
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
stflag = False
while (True):
  if st -time.time() > 1.8:
    stflag = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[i].appendleft(aite)
          dic[aite].appendleft(aiteaite)
      else:
        dic[i].appendleft(aite)
 
  if playcount > 0:
    ans += 1
  else:
    break
if stflag:
  print(int(N * (N-1))//2)
if allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)

Submission status: Runtime Error

Solution code:
def make_tree(index, a_list):
    depth = 1
    for a in a_list:
        x, y = min(index, a), max(index, a)
        depth = max(tree[x, y], depth)
        #tree[x, y] = depth
        #depth += 1

import collections

tree = collections.Counter()

N = int(input())
for n in range(N):
    a_list = list(map(int, input().split()))
    make_tree(n + 1, a_list)
    
if(tree.most_common()[-1][1] != 1):
    print(-1)
else:
    print(tree.most_common()[0][1])

Submission status: Runtime Error

Solution code:
N = int(input())

A = [ [int(i) for i in input().split() ] for j in range(N) ]

for i in range(N):
	A[i].append(-1)
	A[i] = [int(s) for s in A[i]]



# Hはリスト
def search(H):
	list=[]
	counter = 0
	for i in range(N):
		if H.count(i+1) > 0:
			l = H.index(i+1)

			if H[i] == l+1 and l > i:
				list.append((i,l))
				counter += 1

	list.append(counter)
	return list

depth_col = [0]*N

look = []

for _ in range(N):
	look.append(A[_][0])

counter = 0

while min(depth_col) < N-1:
	result = search(look)

	if result[-1] == 0:
		counter = -1
		break
	else:
		lengh_search = len(result)-1
		for j in range(lengh_search):
			x = result[j][0]
			y = result[j][1]
			depth_col[x] += 1
			depth_col[y] += 1

			a = depth_col[x]
			b = depth_col[y]
			look[x] = A[x][a]
			look[y] = A[y][b]

		counter += 1

if counter < 0:
	print(-1)
else:
	
print(counter)

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline

n = int(input())
N =n*(n-1)//2

"""
a = [[min(i,int(j)-1)+max(i,int(j)-1)*(max(i,int(j)-1)-1)//2 for j in readline().split()] for i in range(n)]
g = [[] for i in range(N)]
p = [[] for i in range(N)]
for i in range(n):
    for j in range(n-2):
        g[a[i][j]].append(a[i][j+1])
        p[a[i][j+1]].append(a[i][j])
"""

a = [[int(j)-1 for j in readline().split()] for i in range(n)]

g = {(i,j): [] for i in range(n) for j in range(i+1,n)}
p = {(i,j): [] for i in range(n) for j in range(i+1,n)}
for i in range(n):
    for j in range(n-2):
        if i < a[i][j]:
            ij = (i, a[i][j])
        else:
            ij = (a[i][j],i)
        if i < a[i][j+1]:
            ijj = (i, a[i][j+1])
        else:
            ijj = (a[i][j+1],i)
        g[ij].append(ijj)
        p[ijj].append(ij)


"""
トポロジカルソート
DAG なら
g: グラフの隣接行列
p: 逆辺の隣接行列

q をheapq にしたりすると、辞書順にとりだしたりとかができる。
"""
def topological_sort_queue(g,p):
#    indegree = [len(v) for v in p] # 流入辺の数を数えた配列
#    q = [i for i, c in enumerate(indegree) if c == 0] #流入辺0の点の集合
    indegree = {v:len(vc) for v,vc in p.items()} # 流入辺の数を数えた配列
    q = [i for i, c in indegree.items() if c == 0] #流入辺0の点の集合
    L = [] #ソート結果をためておく配列

    ans = {i:0 for i in g}
    a = 0
    while q:
        v = q.pop()
        L.append(v)
        for c in g[v]: #配る
            ans[c] = max(ans[c],ans[v]+1)
            a = max(a,ans[c])
            indegree[c] -= 1 #辺 node -> child を削除する
            if indegree[c] == 0:
                q.append(c)
    if len(L) != N:
#        print("サイクル検出")
        return -1
    else:
#        return(L)
        return(a+1)        

print(topological_sort_queue(g,p))

assert n != 4