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: Time Limit Exceeded

Solution code:
N = int(input())

A = []
for i in range(N):
  A.append(list(map(lambda x: int(x) - 1, input().split())))
B = [0 for i in range(N)]
C = [-1 for i in range(N)]
d = 0
cnt = 0
max = N * (N-1) // 2
while cnt < max:
  f = False
  for i in range(N):
    if B[i] >= N - 1: continue
    vs = A[i][B[i]]
    if  C[i] == d or C[vs] == d : continue

    if A[vs][B[vs]] == i:
      B[vs] += 1
      B[i] += 1
      C[vs] = d
      C[i] = d
      cnt += 1
      f = True
  if not f: 
    print (-1)
    break
  d += 1
else:
  print (d)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

A = []
for i in range(N):
  A.append(list(map(lambda x: int(x) - 1, input().split())))
B = [0 for i in range(N)]
C = [-1 for i in range(N)]
d = 0
cnt = 0
max = N * (N-1) // 2
while cnt < max:
  f = False
  for i in range(N):
    if B[i] >= N - 1: continue
    vs = A[i][B[i]]
#    if vs >= N - 1: continue
    if A[vs][B[vs]] == i and C[i] != d and C[vs] != d:
      B[vs] += 1
      B[i] += 1
      C[vs] = d
      C[i] = d
      cnt += 1
      f = True
  if not f: 
    print (-1)
    break
  d += 1
else:
  print (d)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [list(map(int, input().split(' ')))]
for i in range(n-1):
    a.append(list(map(int, input().split(' '))))
X = []
next = [0]*n
game = [0]*n
for i in range(n-1):
    X.append([0]*(n-1-i))
x = X
for k in range(int(n*(n-1)/2)+1):
    game = [0]*n
    hantei = 0
    h = 0
    for ii in a:
        if len(ii) != 0:
            h = 1
            break
    if h == 0:
        print(k)
        exit()
    for i, b in enumerate(a):
        if b == [] or game[i] == 1 or next[i] == 1:
            continue
        j = b[0] - 1
        if i < j:
            x[i][j-i-1] += 1   
            if x[i][j-i-1] == 2:
                a[i].pop(0)
                a[j].pop(0)
                next[i] = 0
                next[j] = 0
                game[i] = 1
                game[j] = 1
                hantei = 1
            else:
                next[i] = 1

        else:
            x[j][i-j-1] += 1
            if x[j][i-j-1] == 2:
                a[i].pop(0)
                a[j].pop(0)
                next[i] = 0
                next[j] = 0
                game[i] = 1
                game[j] = 1  
                hantei = 1
            else:
                next[i] = 1
    if hantei == 0:
        print(-1)
        exit()

Submission status: Time Limit Exceeded

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

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


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


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


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


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


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


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


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


def mt(f):
    import time

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

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

    return wrap


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

    s1 = set()
    s2 = set()

    def update(i):
        if not A[i-1]:
            return

        d = A[i-1][-1]
        n = (min(i, d), max(i, d))
        if n not in s1:
            s1.add(n)
        else:
            s2.add(n)
            s1.remove(n)

    for i in range(1, N+1):
        update(i)

    while s2:
        ans += 1
        s2_, s2 = s2, set()
        for k in s2_:
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            update(a)
            update(b)


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


def TSort(g):
    V = set(g.keys())
    for v in g.values():
        V |= set(v)
    V = tuple(V)
    funin = Counter()

    for u in V:
        for v in g[u]:
            funin[v] += 1

    q = deque()
    for v in V:
        if funin[v] == 0:
            q.append(v)
    L = []
    while q:
        u = q.popleft()
        L.append(u)
        for v in g[u]:
            funin[v] -= 1
            if funin[v] == 0:
                q.append(v)
    return L

@mt
def slv2(N, A):
    g = defaultdict(list)
    
    for i, a in enumerate(A):
        i += 1
        for j in range(1, N-1):
            u = (min(i, a[j-1]), max(i, a[j-1]))
            v = (min(i, a[j]), max(i, a[j]))
            g[u].append(v)
    sv = TSort(g)
    if len(sv) != N*(N-1)//2:
        return -1
    
    dp = defaultdict(lambda:0)
    for u in sv:
        for v in g[u]:
            dp[v] = max(dp[v], dp[u]+1)
    return dp[sv[-1]] + 1


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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

A = []
for i in range(N):
  A.append(list(map(lambda x: int(x) - 1, input().split())))
B = [0 for i in range(N)]
C = [0 for i in range(N)]
d = 1
cnt = 0
while cnt < N * (N-1) // 2:
  f = False
  for i in range(N):
    if B[i] >= N - 1: continue
    vs = A[i][B[i]]
    if vs >= N - 1: continue

    if A[vs][B[vs]] == i and C[i] != d and C[vs] != d:
      B[vs] += 1
      B[i] += 1
      C[vs] = d
      C[i] = d
      cnt += 1
      f = True
#    print (cnt, i, B, C, d)
  if not f: 
    print (-1)
    break
  d += 1
else:
  print (d-1)

Submission status: Time Limit Exceeded

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

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


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


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


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


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


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


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


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


def mt(f):
    import time

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

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

    return wrap


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

    s1 = set()
    s2 = set()

    def update(i):
        if not A[i-1]:
            return

        d = A[i-1][-1]
        n = (min(i, d), max(i, d))
        if n not in s1:
            s1.add(n)
        else:
            s2.add(n)
            s1.remove(n)

    for i in range(1, N+1):
        update(i)

    while s2:
        ans += 1
        s2_, s2 = s2, set()
        for k in s2_:
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            update(a)
            update(b)


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


def TSort(g):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = tuple(set(V))
    funin = Counter()

    for u in V:
        for v in g[u]:
            funin[v] += 1

    q = deque()
    for v in V:
        if funin[v] == 0:
            q.append(v)
    L = []
    while q:
        u = q.popleft()
        L.append(u)
        for v in g[u]:
            funin[v] -= 1
            if funin[v] == 0:
                q.append(v)
    return L

@mt
def slv2(N, A):
    g = defaultdict(list)
    
    for i, a in enumerate(A):
        i += 1
        for j in range(1, N-1):
            u = (min(i, a[j-1]), max(i, a[j-1]))
            v = (min(i, a[j]), max(i, a[j]))
            g[u].append(v)
    sv = TSort(g)
    if len(sv) != N*(N-1)//2:
        return -1
    
    dp = defaultdict(lambda:0)
    for u in sv:
        for v in g[u]:
            dp[v] = max(dp[v], dp[u]+1)
    return dp[sv[-1]] + 1


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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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


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


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


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


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


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


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


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


def mt(f):
    import time

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

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

    return wrap


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

    s1 = set()
    s2 = set()

    def update(i):
        if not A[i-1]:
            return

        d = A[i-1][-1]
        n = (min(i, d), max(i, d))
        if n not in s1:
            s1.add(n)
        else:
            s2.add(n)
            s1.remove(n)

    for i in range(1, N+1):
        update(i)

    while s2:
        ans += 1
        s2_, s2 = s2, set()
        for k in s2_:
            a, b = k
            A[a-1].pop()
            A[b-1].pop()
            update(a)
            update(b)


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


def TSort(g):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = set(V)
    funin = Counter()

    for u in V:
        for v in g[u]:
            funin[v] += 1

    q = deque()
    for v in V:
        if funin[v] == 0:
            q.append(v)
    L = []
    while q:
        u = q.popleft()
        L.append(u)
        for v in g[u]:
            funin[v] -= 1
            if funin[v] == 0:
                q.append(v)
    return L

@mt
def slv2(N, A):
    g = defaultdict(list)
    
    for i, a in enumerate(A):
        i += 1
        for j in range(1, N-1):
            u = (min(i, a[j-1]), max(i, a[j-1]))
            v = (min(i, a[j]), max(i, a[j]))
            g[u].append(v)
    sv = TSort(g)
    if len(sv) != N*(N-1)//2:
        return -1
    
    dp = defaultdict(lambda:0)
    for u in sv:
        for v in g[u]:
            dp[v] = max(dp[v], dp[u]+1)
    return dp[sv[-1]] + 1


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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools


import queue

def get_ind(pre_tuple, num):
    a, b = pre_tuple
    ans = (a - 1) * num + b
    return ans



def main():
    num = int(input())
    data = [list(map(int, input().split())) for i in range(num)]

    graph_data = [set() for i in range(num * num)]
    parent_node = [0 for i in range(num * num)]

    for i in range(num):
        now_node = i + 1
        pre_tuple = (0, 0)
        for j in range(num - 1):
            next_node = data[i][j]
            now_tuple = (min(now_node, next_node), max(now_node, next_node))
            if j == 0:
                pass
                # parent_node[now_tuple] += 0
            else:
                index = get_ind(pre_tuple, num)
                # print(index, pre_tuple)
                graph_data[index].add(now_tuple)
                index2 = get_ind(now_tuple, num)
                parent_node[index2] += 1
            pre_tuple = now_tuple
    # sys.exit()

    q = queue.Queue()
    count_node, ans = 0, 0

    for i in range(1, num + 1):
        for j in range(i + 1, num + 1):
            node = (i, j)
            index = get_ind(node, num)
            if parent_node[index] == 0:
                q.put((node, 1))
                count_node += 1

    while not q.empty():
        now_node, length = q.get()
        index = get_ind(now_node, num)
        for next_node in graph_data[index]:
            index2 = get_ind(next_node, num)
            parent_node[index2] -= 1
            if parent_node[index2] == 0:
                q.put((next_node, length + 1))
                count_node += 1

    if count_node < (num * (num - 1)) // 2:
        print(-1)
    else:
        print(length)







if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
N = int(input())

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

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

flag = 0
day = 0
checker_def = set(range(N))
checker = copy.deepcopy(checker_def)
while match_num != 0:
    while bool(checker):
        i = checker.pop()
        if bool(A[i]):
            a = A[i][0]-1
        else:
            checker_def.remove(i)
            continue
        if a not in checker:
            continue
        if A[a][0]-1== i:
            A[i].popleft()
            A[a].popleft()
            checker.remove(a)
            match_num-=1
            flag += 1

    day +=1
    if flag == 0:
        print(-1)       
        exit()

    checker = copy.deepcopy(checker_def)
    flag = 0

print(day)

Submission status: Time Limit Exceeded

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




def main():
    num = int(input())

    link_data = defaultdict(set)
    indegree = defaultdict(int)

    for now_node in range(1, num + 1):
        data = list(map(int, input().split()))
        for j in range(num - 1):
            next_node = data[j]
            now_tuple = (min(now_node, next_node), max(now_node, next_node))
            if j == 0:
                indegree[now_tuple] += 0
            else:
                link_data[pre_tuple].add(now_tuple)
                indegree[now_tuple] += 1
            pre_tuple = now_tuple


    q = queue.Queue()
    count_node = 0

    for node, count in indegree.items():
        if count == 0:
            q.put((node, 1))
            count_node += 1

    while not q.empty():
        now_node, length = q.get()
        for next_node in link_data[now_node]:
            indegree[next_node] -= 1
            if indegree[next_node] == 0:
                q.put((next_node, length + 1))
                count_node += 1

    if count_node < (num * (num - 1)) // 2:
        print(-1)
    else:
        print(length)







if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep="\n") if type(a)!=type("a") else print(a)
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    
    #この試合はこの試合のあとでないといけない、という条件がいくつもあるので
    #クリティカルパスを求めるイメージ(トポロジカルソート)
    #もしDAGでなければ無理なので-1

    N = I()
    A = LLIN_(N)
    matches = set()
    id = [[-inf]*N for _ in range(N)]
    cnt = 0
    for i,a in enumerate(A):
        for j,rival in enumerate(a):
            if i < rival:
                id[i][rival] = cnt
                cnt += 1

    edge = defaultdict(list)

    def to_ID(i,j):
        if i>j:
            i,j = j,i
        return id[i][j]

    for i,a in enumerate(A):
        for j,rival in enumerate(a[:-1]):
            match_id = to_ID(i,rival)
            next_rival = a[j+1]
            next_match_id = to_ID(i,next_rival)
            edge[match_id].append(next_match_id)

    #print(edge.items())
    #pprint(id)
    #print(cnt)

    dp = {}
    visited = set()
    caluculated = set()
    def dfs(match):
        #print("dfs",match,visited,sep="\n")
        if match in visited:
            #print(match,dp)
            if match in caluculated:
                return dp[match]
            else:
                print(-1)
                exit()
        visited.add(match)
        dp[match] = 1
        for next_match in edge[match]:
            #print("match,next",match,next_match)
            dp[match] = max(dfs(next_match)+1, dp[match])

        #print(match,dp[match])
        caluculated.add(match)
        return dp[match]

    ans = 0
    for match in range(cnt):
        res = dfs(match)
        #print(res)
        ans = max(ans,res)
    print(ans)




    """#O(試合数)
    N = I()
    A = []
    #消化した試合は削除していく
    for _ in range(N):
        *a, = reversed(LI_())
        A.append(a)
    #pprint("A",A)
    
    match = set()
    for i,a in enumerate(A):
        rival = a[-1]
        rival_of_rival = A[rival][-1]
        if rival_of_rival == i:
            match.add(i)
            match.add(rival)

    
    day = 0
    while match:
        day += 1
        last_match = set()
        last_match,match = match,last_match

        for i in last_match:
            A[i].pop()
        
        for i in last_match:
            if A[i]:
                rival = A[i][-1]
                rival_of_rival = A[rival][-1]
                if rival_of_rival == i:
                    match.add(i)
                    match.add(rival)
    for a in A:
        if a:
            print(-1)
            exit()

    print(day)"""

    """ O(N^3)
    N = I()
    A = LLIN_(N)
    indexes = [0] * N
    cnt = 0
    match = set()
    for i in range(N*N):
        update = False
        today_players = set()
        for k in range(N):
            index = indexes[k]
            if index >= N-1: #全試合done
                continue
            rival = A[k][index]
            if (k,rival) in match: #前回の希望相手との試合がまだ
                continue
            if (rival,k) in match :
                if not {k,rival} & today_players:
                    cnt += 1
                    update = True
                    match.remove((rival,k))
                    today_players.add(k)
                    today_players.add(rival)
                    indexes[k] += 1
                    indexes[rival] += 1
            else:
                match.add((k,rival))


            
        if not update:
            if cnt != (N*(N-1))//2:
                print(-1)
                exit()
            else:
                print(i)
                exit()"""

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())

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

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

flag = 0
day = 0
checker = set()
while match_num != 0:
    for i in range(N):
        if bool(A[i]) == False:
            continue
        if i in checker:
            continue
        a = A[i][0]-1
        if a in checker:
            continue
        if A[a][0]-1== i:
            A[i].popleft()
            A[a].popleft()
            checker.add(a)
            checker.add(i)
            match_num-=1
            flag = True

    day +=1
    if flag == 0:
        print(-1)       
        exit()

    checker = set()
    flag = False

print(day)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools


import queue




def main():
    num = int(input())
    data = [list(map(int, input().split())) for i in range(num)]

    graph_data = defaultdict(set)
    parent_node = defaultdict(int)

    for i in range(num):
        now_node = i + 1
        pre_tuple = (0, 0)
        for j in range(num - 1):
            next_node = data[i][j]
            now_tuple = (min(now_node, next_node), max(now_node, next_node))
            if j == 0:
                parent_node[now_tuple] += 0
            else:
                graph_data[pre_tuple].add(now_tuple)
                parent_node[now_tuple] += 1
            pre_tuple = now_tuple


    # q = queue.Queue()
    count_node, ans = 0, 0
    now_set = set()
    next_set = set()

    for node, count in parent_node.items():
        if count == 0:
            # q.put((node, 1))
            now_set.add((node, 1))
            count_node += 1

    while len(now_set):
        for now_node, length in now_set:
            for next_node in graph_data[now_node]:
                parent_node[next_node] -= 1
                if parent_node[next_node] == 0:
                    # q.put((next_node, length + 1))
                    next_set.add((next_node, length + 1))
                    count_node += 1
        now_set = next_set
        next_set = set()

    if count_node < (num * (num - 1)) // 2:
        print(-1)
    else:
        print(length)







if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())

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

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

q = []
a_tmp = []
flag = 0
day = 0
checker = set()
while match_num != 0:
    for i in range(N):
        if bool(A[i]) == False:
            continue
        if i in checker:
            continue
        a = A[i][0]-1
        if a in checker:
            continue
        if A[a][0]-1== i:
            A[i].popleft()
            A[a].popleft()
            checker.add(a)
            checker.add(i)
            match_num-=1
            flag += 1

    day +=1
    if flag == 0:
        print(-1)       
        exit()

    checker = set()
    flag = 0

print(day)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())

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

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

q = []
a_tmp = []
flag = 0
day = 0
checker = set()
while match_num != 0:
    for i in range(N):
        if i in checker:
            continue
        if bool(A[i]) == False:
            continue
        a = A[i][0]-1
        if a in checker:
            continue
        if A[a][0]-1== i:
            A[i].popleft()
            A[a].popleft()
            checker.add(a)
            checker.add(i)
            match_num-=1
            flag += 1

    day +=1
    if flag == 0:
        print(-1)       
        exit()

    checker = set()
    flag = 0

print(day)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools


import queue




def main():
    num = int(input())
    data = [list(map(int, input().split())) for i in range(num)]

    graph_data = defaultdict(set)
    parent_node = defaultdict(int)
    length_data = defaultdict(int)

    for i in range(num):
        now_node = i + 1
        pre_tuple = (0, 0)
        for j in range(num - 1):
            next_node = data[i][j]
            now_tuple = (min(now_node, next_node), max(now_node, next_node))
            length_data[now_tuple] = 0
            if j == 0:
                parent_node[now_tuple] += 0
            else:
                graph_data[pre_tuple].add(now_tuple)
                parent_node[now_tuple] += 1
            pre_tuple = now_tuple


    q = queue.Queue()
    count_node, ans = 0, 0

    for node, count in parent_node.items():
        if count == 0:
            q.put((node, 1))
            count_node += 1

    while not q.empty():
        now_node, length = q.get()
        if length < length_data[now_node]:
            continue

        for next_node in graph_data[now_node]:
            parent_node[next_node] -= 1
            if parent_node[next_node] == 0:
                q.put((next_node, length + 1))
                count_node += 1
                length_data[next_node] = max(length + 1, length_data[next_node])

    if count_node < (num * (num - 1)) // 2:
        print(-1)
    else:
        print(length)







if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools


import queue




def main():
    num = int(input())
    data = [list(map(int, input().split())) for i in range(num)]

    graph_data = defaultdict(set)
    parent_node = defaultdict(int)

    for i in range(num):
        now_node = i + 1
        pre_tuple = (0, 0)
        for j in range(num - 1):
            next_node = data[i][j]
            now_tuple = (min(now_node, next_node), max(now_node, next_node))
            if j == 0:
                parent_node[now_tuple] += 0
            else:
                graph_data[pre_tuple].add(now_tuple)
                parent_node[now_tuple] += 1
            pre_tuple = now_tuple


    q = queue.Queue()
    count_node, ans = 0, 0

    for node, count in parent_node.items():
        if count == 0:
            q.put((node, 1))
            count_node += 1

    while not q.empty():
        now_node, length = q.get()
        for next_node in graph_data[now_node]:
            parent_node[next_node] -= 1
            if parent_node[next_node] == 0:
                q.put((next_node, length + 1))
                count_node += 1

    if count_node < (num * (num - 1)) // 2:
        print(-1)
    else:
        print(length)







if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy
n=int(input())
a=[]
for i in range(n):
  a.append(list(map(int,input().split())))
maxmatch=n*(n-1)
day=0
q=[i for i in range(n)]
nq=[]
match=[0]*(n+1)
check=[0]*(n+1)
while q:
  day+=1
  for i in q:
    if match[i]==n-1 or check[i]==day:
      continue
    else:
      vs=a[i][match[i]]-1
      if check[vs]!=day and check[i]!=day and a[vs][match[vs]]-1==i and a[i][match[i]]-1==vs:
        match[i]+=1
        match[vs]+=1
        match[n]+=2
        check[i]=day
        check[vs]=day
        check[n]=day
        nq.append(i)
        nq.append(vs)
      
    if i==q[-1]:
      if check[n]!=day:
        print(-1)
        sys.exit()
  if match[n]==maxmatch:
    break
  q=copy.copy(nq)
  nq=[]
        
print(day)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools


import queue




def main():
    num = int(input())
    data = [list(map(int, input().split())) for i in range(num)]

    graph_data = defaultdict(set)
    parent_node = defaultdict(int)

    for i in range(num):
        now_node = i + 1
        pre_tuple = (0, 0)
        for j in range(num - 1):
            next_node = data[i][j]
            now_tuple = (min(now_node, next_node), max(now_node, next_node))
            if j == 0:
                parent_node[now_tuple] += 0
            else:
                graph_data[pre_tuple].add(now_tuple)
                parent_node[now_tuple] += 1
            pre_tuple = now_tuple


    q = queue.Queue()
    count_node, ans = 0, 0

    for i in range(1, num + 1):
        for j in range(i + 1, num + 1):
            node = (i, j)
            if parent_node[node] == 0:
                q.put((node, 1))
                count_node += 1

    while not q.empty():
        now_node, lenth = q.get()
        # print(now_node, lenth)
        ans = max(ans, lenth)
        for next_node in graph_data[now_node]:
            parent_node[next_node] -= 1
            if parent_node[next_node] == 0:
                q.put((next_node, lenth + 1))
                count_node += 1

    if count_node < (num * (num - 1)) // 2:
        print(-1)
    else:
        print(ans)







if __name__ == '__main__':
    main()