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: Accepted

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

new = []
wait = []
for i in range(n):
    new.append(i)
    wait.append(a[i][0])

progress = [0] * n
day = 0
finished = []
while len(finished) < n:
    visited = []
    for i in new:
        _wait = wait[i] - 1

        if _wait != float('inf') and wait[_wait] == i + 1 and _wait not in visited and i not in visited:
            progress[i] += 1
            progress[_wait] += 1
            visited.append(i)
            visited.append(_wait)

            if progress[i] != n - 1:
                wait[i] = a[i][progress[i]]
            else:
                wait[i] = float('inf')
                finished.append(i)

            if progress[_wait] != n - 1:
                wait[_wait] = a[_wait][progress[_wait]]
            else:
                wait[_wait] = float('inf')
                finished.append(_wait)

    # print(visited, progress)
    if not visited:
        day = -1
        break

    new = []
    for i in range(len(visited)):
        new.append(visited[i])

    day += 1


print(day)

Submission status: Accepted

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 = 1
    empty = 0
    candidates = set(range(N))
    while True:
        used = set()
        for i in candidates:
            if len(A[i]) == 0 or i in used:
                continue
            j = A[i][0]
            if len(A[j]) and A[j][0] == i and j not in used:
                used.add(i)
                used.add(j)
                A[i].popleft()
                A[j].popleft()
                if len(A[i]) == 0:
                    empty += 1
                if len(A[j]) == 0:
                    empty += 1
        if empty == N:
            break
        if len(used) == 0:
            ans = -1
            break
        ans += 1
        candidates = used
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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=[0,0]
while count!=n*(n-1)//2 and day<=10**4:
  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[0]=check[1]
  check[1]=count
  if check[0]==check[1]:
    print(-1)
    sys.exit()
if day>10**4:
  print(n*(n-1)//2)
  sys.exit()
print(day)

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
N = int(input())
A = [0] + [list(map(lambda x: tuple(sorted((i, int(x)))), input().split())) for i in range(1, N+1)]
Idx = [0]*(N+1)
pool = set()  # 対局待ち
q = deque([a[0] for a in A[1:]])
#day = [set() for _ in range(N*(N-1)//2)]
ans = 1
s = set()
while q:
    #print(pool, q)
    p = q.popleft()
    if p in pool:
        pool.remove(p)
        a, b = p
        Idx[a] += 1
        Idx[b] += 1
        if a in s or b in s:
            ans += 1
            s = {a, b}
        else:
            s.add(a)
            s.add(b)
        if Idx[a]<N-1:
            q.append(A[a][Idx[a]])
        if Idx[b]<N-1:
            q.append(A[b][Idx[b]])
    else:
        pool.add(p)
if pool:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    s = S()
    t = S()
    ans = 0
    for i in range(len(s)):
        if s[i] == t[i]:
            ans += 1
    print(ans)
    return

#B
def B():
    a,b = LI()
    for i in range(10000):
        if 1+i*a-i >= b:
            print(i)
            return
    return

#C
def C():
    n = I()
    a = LI()
    ans = 0
    r = 1
    for l in range(n):
        if r == l:
            r += 1
        while r < n and a[r-1] >= a[r]:
            r += 1
        ans = max(ans, r-l-1)
    print(ans)
    return

#D
def D():
    n = I()
    print(n*(n-1)>>1)
    return

#E
def E():
    def dfs(x,p):
        if dp[x] != None:
            return dp[x]
        dp[x] = -1
        for y in v[x]:
            if p[y]:
                dp[x] = float("inf")
                break
            p[y] = 1
            dp[x] = max(dp[x], dfs(y,p)+1)
            p[y] = 0
        return dp[x]

    n = I()
    a = LIR(n)
    for i in range(n):
        for j in range(n-1):
            a[i][j] -= 1
    m = n*(n-1)
    v = [[] for i in range(m)]
    for i in range(n):
        p = n*min(i, a[i][0]) + max(i, a[i][0])
        for j in range(n-2):
            p_ = n*min(i, a[i][j+1]) + max(i, a[i][j+1])
            v[p_].append(p)
            p = p_
    dp = defaultdict(lambda : None)
    for i in range(m):
        if not v[i]:
            dp[i] = 1
    ans = 1
    p = [0]*m
    for x in range(m):
        p[x] = 1
        if ans < dfs(x,p):
            ans = dp[x]
        p[x] = 0
    if ans == float("inf"):
        print(-1)
    else:
        print(ans)
    return

#F
def F():
    n = I()
    p = LIR(n)

    return

#Solve
if __name__ == "__main__":
    E()

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
import sys
import heapq
import math

# input = sys.stdin.readline

sys.setrecursionlimit(1000000000)

MIN = -10 ** 9
MOD = 10 ** 9 + 7


def main():
    N = int(input())
    # A, B = [int(a) for a in input().split()]
    # H = [int(a) for a in input().split()]
    A = {
        i: list(reversed([int(a) - 1 for a in input().split()]))
        for i in range(N)
    }

    Q = set(range(N))

    count = 0
    while True:
        pool = []
        for i in Q:
            ai = A[i]
            if len(ai) == 0:
                continue
            target = ai[-1]
            # if target < i:
            #     continue
            target_q = A[target]
            if target_q[-1] == i:
                # print(i,target)
                pool.append(i)
                pool.append(target)

        if len(pool) == 0:
            if len(Q) != 0:
                print(-1)
                return
            else:
                raise ValueError("test")

        qq = []
        for i in set(pool):
            A[i].pop()
            if len(A[i]) != 0:
                qq.append(i)
        Q = set(qq)

        count += 1
        if len(Q) == 0:
            print(count)
            return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def solve_e(n, a_list):
    days = 0
    ind_list = [0] * n
    match_count = 0
    queue = list(range(n))
    stack = dict()
    while len(queue) > 0:
        days += 1
        new_queue = []
        for p in queue:
            if ind_list[p] < n - 1:
                q = a_list[p][ind_list[p]] - 1
                k = str(min(p, q)) + "_" + str(max(p, q))
                if k in stack.keys():
                    ind_list[p] += 1
                    ind_list[q] += 1
                    # print(days, p, q)
                    new_queue.append(p)
                    new_queue.append(q)
                    match_count += 1
                else:
                    stack[k] = 1
        queue = new_queue
    if match_count == n * (n - 1) // 2:
        return days - 1
    else:
        return -1


def test():
    N = 1000
    A_list = []
    for i in range(N):
        A_list.append(list(range(1, i + 1)) + list(range(i + 2, N + 1)))
    print(solve_e(N, A_list))


def main():
    N = int(input())
    A_list = []
    for _ in range(N):
        A_list.append(list(map(int, input().split())))
    print(solve_e(N, A_list))


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

NN=(N*(N-1))//2
edges=[[] for _ in range(NN)]
nums = [0]*NN

for i in range(N):
    sis=[0]*(N-1)
    for j in range(N-1):
        src, dst = sorted([i,A[i][j]-1])
        sis[j] = inds[src][dst]

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

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

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

if cnt < NN:
    print(-1)
else:
    print(ans)

Submission status: Accepted

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
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: Accepted

Solution code:
N = int(input())

from collections import defaultdict,deque

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

count = 0
B = defaultdict(int)
now_list = [0]*N
day=0

Q = deque([i for i in range(N)])
while count<(N*(N-1))//2:
        Q2 = deque([])
        battle_flag=False
        while len(Q)>0:
                i = Q.popleft()
                j = A[i][now_list[i]]-1
                a=min(i,j)
                b=max(i,j)
                if B[str(a)+" "+str(b)]==1:
                        count+=1
                        B[str(a)+" "+str(b)]=0
                        now_list[i]+=1
                        now_list[j]+=1
                        if now_list[i]<N-1:
                                Q2.append(i)                                
                        if now_list[j]<N-1:
                                Q2.append(j)                                
                        battle_flag=True
                else:
                        B[str(a)+" "+str(b)]+=1
        if not battle_flag:
                break
        Q = Q2
        day+=1

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

Submission status: Accepted

Solution code:
n=int(input())
a=[]
l=[[] for i in range(n)]
ind=[0 for i in range(n)]
s=set()
ans=1
from collections import deque
q=deque([])
for i in range(n):
    tmp=[int(j)-1 for j in input().split()]
    a.append(tmp)
    for j in tmp:
        if i<j:
            l[i].append((i,j))
        else:
            l[i].append((j,i))
    q.append(l[i][0])
ll=[]
while q:
    p=q.popleft()
    if p in s:
        s.remove(p)
        i,j=p
        if i in ll or j in ll:
            ans+=1
            ll=[i,j]
        else:
            ll.append(i)
            ll.append(j)
        if ind[i]<n-2:
            ind[i]+=1
            q.append(l[i][ind[i]])
        if ind[j]<n-2:
            ind[j]+=1
            q.append(l[j][ind[j]])
    else:
        s.add(p)

for i in range(n):
    if ind[i]!=n-2:
        print(-1)
        exit()
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
X = [[int(a)-1 for a in input().split()] for _ in range(N)]
Y = [0] * N
Z = [-1] * N

L = [a for a in range(N)]
f = 1
d = 0
c = 0
while f:
    d += 1
    f = 0
    NL = []
    for l in L:
        a, aa = Y[l], Z[l]
        if a >= N - 1: continue
        ll = X[l][a]
        b, bb = Y[ll], Z[ll]
        if b >= N - 1: continue
        lll = X[ll][b]
        if lll == l and aa < d and bb < d:
            f = 1
            c += 1
            Y[l] += 1
            Z[l] = d
            if Y[l] < N - 1: NL.append(l)
            Y[ll] += 1
            Z[ll] = d
            if Y[ll] < N - 1: NL.append(ll)
    if c == N*(N-1)//2:
        print(d)
        break
    L = NL
else:
    print(-1)

Submission status: Accepted

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

cnt = [0] * N

S = []
for i in range(N):
  t = A[i][cnt[i]] - 1
  if i == A[t][cnt[t]] - 1:
    if cnt[i] != N - 2:
      S.append(i)

ans = 1
L = [True] * N
while S:
  ans += 1
  for i in S:
    cnt[i] += 1
    L[i] = True
  T = []
  for i in S:
    if L[i]:
      t = A[i][cnt[i]] - 1
      if i == A[t][cnt[t]] - 1:
        if cnt[i] != N - 2:
          L[i] = False
          T.append(i)
        if L[t]:
          L[t] = False
          if cnt[t] != N - 2:
            T.append(t)
  S = T

for i in range(N):
  if cnt[i] != N - 2:
    print(-1)
    break
else:
  print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict

N = int(input())
A = [list(map(lambda x:int(x)-1,input().split()))[::-1] for _ in range(N)]
d = defaultdict(lambda:0)
q = []
for i in range(N):
    j = A[i].pop()
    i,j = min(i,j),max(i,j)
    d[(i,j)] += 1
    if d[(i,j)] == 2:
        q.append((i,j))

ans = 0
while q:
    ans += 1
    q_ = []
    for i,j in q:
        if A[i]:
            i_ = A[i].pop()
            i,i_ = min(i,i_),max(i,i_)
            d[(i,i_)] += 1
            if d[(i,i_)] == 2:
                q_.append((i,i_))
        if A[j]:
            j_ = A[j].pop()
            j,j_ = min(j,j_),max(j,j_)
            d[(j,j_)] += 1
            if d[(j,j_)] == 2:
                q_.append((j,j_))
    q = q_

f = True
for i in range(N):
    if A[i]:
        f = False

if f:
    print(ans)
else:
    print(-1)

Submission status: Accepted

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

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

n = int(input())
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)]

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

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])
        
#print(g)
#print(p)

ans = [0]*(N)

indegree = [len(v) for v in p] # 流入辺の数を数えた配列
Source = [i for i, c in enumerate(indegree) if c == 0] #流入辺0の点の集合
#L = [] #ソート結果をためておく配列
num = 0
while Source:
    node = Source.pop()
    #L.append(node)
    num += 1
    for child in g[node]:
        indegree[child] -= 1 #辺 node -> child を削除する
        if ans[child] < ans[node]+1: ans[child] = ans[node]+1     
        if indegree[child] == 0:
            Source.append(child)

#print(num)
if num != N:
    print(-1)
else:
    print(max(ans)+1)

#print(ans)

Submission status: Accepted

Solution code:
from collections import deque

def solve():
    n = int(input())
    a = []
    for i in range(n):
        ai = [int(j)-1 for j in input().split()]
        a.append(deque(ai))

    d = set()
    # 必ず(i < j)なるように入れる
    q = deque()
    for i in range(n):
        ai = a[i].popleft()
        if i < ai:
            q.append((i, ai))
        else:
            q.append((ai, i))

    ans = 0
    while q:
        ans += 1
        nxt_q = deque()
        while q:
            i, ai = q.pop()
            if (i, ai) in d:
                if a[i]:
                    ni = a[i].popleft()
                    if i < ni:
                        nxt_q.append((i, ni))
                    else:
                        nxt_q.append((ni, i))
                if a[ai]:
                    ni = a[ai].popleft()
                    if ai < ni:
                        nxt_q.append((ai, ni))
                    else:
                        nxt_q.append((ni, ai))
            else:
                d.add((i, ai))
        q = nxt_q

    # 残ってないかチェック
    if any(i for i in a):
        ans = -1
    print(ans)

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from collections import deque
N = int(readline())
G = [[] for i in range(N*N)]
deg = [0]*(N*N)
day = [0]*(N*N)
F = set()
for p in range(N):
    *A, = map(int, readline().split())
    for k in range(N-1):
        A[k] -= 1
    for k in range(N-2):
        i = A[k]+p*N if A[k] < p else p+A[k]*N
        j = A[k+1]+p*N if A[k+1] < p else p+A[k+1]*N
        G[i].append(j)
        deg[j] += 1
    i = A[0]+p*N if A[0] < p else p+A[0]*N
    F.add(i)
que = deque()
for i in F:
    if deg[i] == 0:
        que.append(i)
        day[i] = 1
rest = N*(N-1)//2
while que:
    v = que.popleft()
    rest -= 1
    d = day[v]
    for w in G[v]:
        deg[w] -= 1
        if deg[w] == 0:
            day[w] = day[v] + 1
            que.append(w)
if rest > 0:
    print(-1)
else:
    print(max(day))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

N = int(input())
A = [[-1] + [int(x)-1 for x in row.split()][::-1] for row in sys.stdin.readlines()]

A.append([-1])

def f(cand):
    cand1 = set()
    can_use = []
    for n in cand:
        if A[A[n][-1]][-1] == n:
            can_use.append(n)
    for n in can_use:
        A[n].pop()
        cand1.add(n)
        if A[n][-1] != -1:
            cand1.add(A[n][-1])
    return len(can_use),cand1

answer = 0
rest = N*(N-1)
cand = set(range(N))
while True:
    answer += 1
    x,cand = f(cand)
    if x == 0:
        answer = -1
        break
    rest -= x
    if rest == 0:
        break

print(answer)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from collections import deque

# 入力
n = ni()
graph = [[] for _ in range(n*n)]

# グラフを構築
ins = [0]*(n*n)
for i in range(n):
    jlist = list(li_())
    for j1, j2 in zip(jlist[:-1], jlist[1:]):
        node1 = max(i, j1)*n + min(i, j1)
        node2 = max(i, j2)*n + min(i, j2)
        graph[node1].append(node2)
        ins[node2] += 1

# 最長経路
visited = [False]*(n*n)
for i in range(n):
    visited[i*n + i] = True

# 入次数0をqueに詰める
que = deque()
for i, insi in enumerate(ins):
    if insi == 0:
        que.append((i, 1))

# queがなくなるまで距離を記録
dist = [0]*(n*n)
while que:
    cur, d = que.popleft()

    visited[cur] = True
    dist[cur] = d
    for nex in graph[cur]:
        if not visited[nex]:
            ins[nex] -= 1
            if ins[nex] == 0:
                que.append((nex, d+1))

# 訪れてないノードがあれば-1
ok = True
for vi in visited:
    if not vi:
        ok = False


ans = 0
for di in dist:
    ans = max(ans, di)

print(-1 if not ok else ans)

Submission status: Accepted

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

c = [0 for _ in range(N + 1)]
p = []
for i in range(1, N + 1):
    j = A[i][c[i]]
    if i == A[j][c[j]] and i < j:
        p.append((i, j))
ans = 0
while p:
    # print(p)
    q = []
    for i, j in p:
        c[i] += 1
        c[j] += 1
        if c[i] < N - 1:
            k = A[i][c[i]]
            if A[k][c[k]] == i:
                q.append((i, k))
        if c[j] < N - 1:
            k = A[j][c[j]]
            if A[k][c[k]] == j:
                q.append((j, k))
    ans += 1
    p = q

ans = (
    ans if all(c[i] == N - 1 for i in range(1, N + 1)) else
    -1
)
print(ans)

Submission status: Accepted

Solution code:
rr = raw_input
rri = lambda: int(raw_input())
rrm = lambda: map(int, raw_input().split())

from collections import deque
def solve(N, A):
    ans = 0
    todo = N * (N-1)
    to_inspect = range(N)
    while True:
        ans += 1
        found = False
        to_inspect2 = set()
        for i in to_inspect:
            row = A[i]
            if row:
                j = row[0]
                if (i not in to_inspect2 and j not in to_inspect2 and
                        A[j] and A[j][0] == i):
                    row.popleft()
                    A[j].popleft()
                    found = True
                    todo -= 2
                    to_inspect2.add(i)
                    to_inspect2.add(j)
        if not todo: return ans
        if not found: return -1
        to_inspect = to_inspect2


N = rri()
A = []
for _ in xrange(N):
    row = rrm()
    A.append(deque(x-1 for x in row))
print solve(N, A)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)

def main():
    n = I()
    a = [LI_() for _ in range(n)]
    r = 0
    c = collections.defaultdict(int)
    q = list(range(n))
    t = [0] * n
    while q:
        r += 1
        nq = []
        for i in q:
            j = a[i][t[i]]
            k = i
            if k < j:
                j,k = k,j
            c[(j,k)] += 1
            if c[(j,k)] == 2:
                t[j] += 1
                t[k] += 1
                if t[j] < n-1:
                    nq.append(j)
                if t[k] < n-1:
                    nq.append(k)
        q = nq

    for tt in t:
        if tt != n-1:
            return -1

    return r


print(main())

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin

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

n = ni()
a = []
for i in range(n):
    a.append(na())

def code(l, r, of):
    if l > r:
        l, r = r, l
    return of[l] + r-l-1

of = [0] * (n+1)
for i in range(n):
    of[i+1] = of[i] + n-i-1
g = [[] for _ in range(n*(n-1)//2)]
for i in range(n):
    for j in range(n-2):
        fcode = code(i, a[i][j]-1, of)
        tcode = code(i, a[i][j+1]-1, of)
        g[fcode].append(tcode)

def sort_topologically(g):
    n = len(g)
    ec = [0] * n
    for i in range(n):
        for e in g[i]:
            ec[e] += 1
    ret = [0] * n
    q = 0

    for i in range(n):
        if ec[i] == 0:
            ret[q] = i
            q += 1

    p = 0
    while p < q:
        for to in g[ret[p]]:
            ec[to] -= 1
            if ec[to] == 0:
                ret[q] = to
                q += 1
        p += 1

    for i in range(n):
        if ec[i] > 0:
            return None
    return ret

od = sort_topologically(g)
if not od:
    print(-1)
else:
    dp = [1] * (n*(n-1)//2)
    for i in range(n*(n-1)//2):
        for e in g[od[i]]:
            dp[e] = max(dp[e], dp[od[i]] + 1)
    print(max(dp))

Submission status: Runtime Error

Solution code:
"""
最長経路問題として解く。

各試合のノードを作成。
各試合ノードごとに、「この試合が終わったら、次はこの試合ができるようになる。」という対応関係を作っていく。
"""
def main():
    import sys
    input = sys.stdin.readline
    from collections import deque

    N = int(input())

    A = [[0]*(N)]
    for _ in range(N):
        A.append([0]+list(map(int,input().split())))
    
    #選手iにとって、選手jが何番目の相手かを逆引きするメモを用意しておく。
    reverseMemo = {i:{} for i in range(1,N+1)}
    for i in range(1,N+1):
        for j in range(1,N):
            a = A[i][j]
            reverseMemo[i][a] = j

    #edges[(i,j)] => (i,j)の試合が終わらないと開始できない試合＝iにとってjの次の対戦相手の試合＆jにとってiの次の対戦相手との試合
    edges = {}
    for i in range(1,N+1):
        for j in range(i+1,N+1):
            match = (i,j)
            edges[match] = []
            if reverseMemo[i][j] != N-1:
                nx = A[i][reverseMemo[i][j]+1]
                edges[match].append((min(i,nx),max(i,nx)))
            if reverseMemo[j][i] != N-1:
                nx = A[j][reverseMemo[j][i]+1]
                edges[match].append((min(j,nx),max(j,nx)))
    
    #edges[(i,j)] => (i,j)の試合を開始する前に消化しなくては行けない試合＝iにとってjの前の対戦相手との試合＆jにとってiの前の対戦相手との試合
    reverseEdges = {}
    for k,vs in edges.items():
        if k not in reverseEdges:
            reverseEdges[k] = []
        for v in vs:
            if v not in reverseEdges:
                reverseEdges[v] = []
            reverseEdges[v].append(k)
    
    del reverseMemo
    del A
    
    que = []
    for k,vs in reverseEdges.items():
        if len(vs) == 0:
            que.append((k,1))
    que = deque(que)
    endMatch = set()

    if not que:
        print(-1)
        exit()
    
    cnt = 0
    ans = 0
    while que:
        cnt += 1
        if cnt > n*n:
            print(-1)
            exit()
        match,day = que.popleft()
        for preMatch in reverseEdges[match]:
            if preMatch not in endMatch:
                break
        else:
            endMatch.add(match)
            ans = max(ans,day)
            for nxMatch in edges[match]:
                que.append((nxMatch,day+1))
    print(ans)
main()

Submission status: Runtime Error

Solution code:
sys.setrecursionlimit(10000)

n=int(input())
a=[[0]*(n-1) for i in range(n)]
id=[[-1]*(n) for i in range(n)]
MAXV=n*(n-1)//2
to=[[]*(n) for i in range(MAXV)]
  
def toId(i,j):
  if (i>j):
    i,j=j,i
  return id[i][j]


visited=[False]*MAXV
calculated=[False]*MAXV
dp=[0]*MAXV
def dfs(v):
  if visited[v]:
    if not calculated[v]:
      return -1
    return dp[v]
  visited[v]=True
  dp[v]=1
  for u in to[v]:
    res = dfs(u)
    if res==-1:
      return -1
    dp[v]=max(dp[v], res+1)
  calculated[v]=True
  return dp[v]


def main():
  for i in range(n):
    a[i]=list(map(lambda x:int(x)-1,input().split()))
  v=0
  for i in range(n):
    for j in range(n):
      if i<j:
        id[i][j]=v
        v+=1
  for i in range(n):
    for j in range(n-1):
      a[i][j]=toId(i,a[i][j])
    for j in range(n-2):
      to[a[i][j+1]].append(a[i][j])
      
  ans=0
  for i in range(v):
    res=dfs(i)
    if res==-1:
      print(-1)
      exit(0)
    ans=max(ans, res)

  print(ans)
  
  
  
if __name__=='__main__':
  main()

Submission status: Runtime Error

Solution code:
n=int(input())
a=[[0]*(n-1) for i in range(n)]
id=[[-1]*(n) for i in range(n)]
MAXV=n*(n-1)//2
to=[[]*(n) for i in range(MAXV)]
  
def toId(i,j):
  if (i>j):
    i,j=j,i
  return id[i][j]


visited=[False]*MAXV
calculated=[False]*MAXV
dp=[0]*MAXV
def dfs(v):
  if visited[v]:
    if not calculated[v]:
      return -1
    return dp[v]
  visited[v]=True
  dp[v]=1
  for u in to[v]:
    res = dfs(u)
    if res==-1:
      return -1
    dp[v]=max(dp[v], res+1)
  calculated[v]=True
  return dp[v]


def main():
  for i in range(n):
    a[i]=list(map(lambda x:int(x)-1,input().split()))
  v=0
  for i in range(n):
    for j in range(n):
      if i<j:
        id[i][j]=v
        v+=1
  for i in range(n):
    for j in range(n-1):
      a[i][j]=toId(i,a[i][j])
    for j in range(n-2):
      to[a[i][j+1]].append(a[i][j])
      
  ans=0
  for i in range(v):
    res=dfs(i)
    if res==-1:
      print(-1)
      exit(0)
    ans=max(ans, res)

  print(ans)
  
  
  
if __name__=='__main__':
  main()

Submission status: Runtime Error

Solution code:
def main():
    import sys
    sys.setrecursionlimit(3000000)

    N = int(input())
    A = [[0]*(N)]
    for _ in range(N):
        A.append([0]+list(map(int,input().split())))

    #選手iにとって、選手jが何番目の相手かを逆引きするメモを用意しておく。
    reverseMemo = {i:{} for i in range(1,N+1)}
    for i in range(1,N+1):
        for j in range(1,N):
            a = A[i][j]
            reverseMemo[i][a] = j

    dp = [[0]+[None]*N for _ in range(N+1)]

    def f(i,j,cnt):
        #iとjの試合が最速でいつできるかを返す。
        if cnt > N*N:
            print(-1)
            exit()
        if dp[i][j] == None and dp[j][i] == None:
            #iの一つ前の試合がいつおわるかを調べる。
            pre = A[i][reverseMemo[i][j]-1]
            tmp1 = f(i,pre,cnt+1)
            
            #jの一つ前の試合がいつおわるかを調べる。
            pre = A[j][reverseMemo[j][i]-1]
            tmp2 = f(j,pre,cnt+1)

            dp[i][j] = max(tmp1,tmp2)+1

        elif dp[i][j] == None and dp[j][i] != None:
            dp[i][j] = dp[j][i]
        elif dp[i][j] != None and dp[j][i] != None:
            dp[j][i] = dp[i][j]
        return dp[i][j]

    ans = 0
    cnt = 0
    for i in range(1,N+1):
        for j in range(1,N):
            cnt += 1
            if cnt > 2:
                print("good")
            a = A[i][j]
            ans = max(ans,f(i,a,0))
    print(ans)
main()