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:
import sys

sys.setrecursionlimit(10 ** 7)

N = int(input())
_match = {}
for i in range(N):
    _match[i + 1] = [int(j) for j in input().split(' ')]

all_match_count = N * (N-1) // 2
match = []
for p, lst in _match.items():
    result = []
    for t in lst:
        if p > t:
            result.append('{}-{}'.format(t, p))
        else:
            result.append('{}-{}'.format(p, t))
    match.append(result)

today_match = set()
already_finish = set()
finish_count = 0
result = 0
while True:
    could_make_match = False
    for i in range(N):
        try:
            c = match[i][0]
        except IndexError:
            continue
        # 試合が見つかった
        if c in today_match:
            today_match.remove(c)
            already_finish.add(c)
            finish_count += 1
            # 対になる試合を探す
            for j in range(i):
                try:
                    _c = match[j][0]
                except IndexError:
                    continue
                if _c in already_finish:
                    match[j].pop(0)
                    break
            match[i].pop(0)
            could_make_match = True
        else:
            today_match.add(c)
        #print(today_match, already_finish)
    if not could_make_match:
        result = -1
        break
    result += 1
    #print('day' + str(result))
    today_match = set()
    if finish_count == all_match_count:
        break

print(result)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
A = [[]]
for i in range(N):
    A.append(deque(map(int,input().split())))
checklist = [-1] * (N+1)
day = 0
total = 0
flg = True
#どうせTLE
while total < (N*(N-1)//2) and flg:
    flg = False
    for i in range(1,N+1):
        if A[i] and A[i][0]:
            enemy = A[i][0]
            if A[enemy][0] == i and checklist[enemy] < 0 and checklist[i] < 0:
                checklist[i] = 1
                checklist[enemy] = 1
                A[enemy].popleft()
                A[i].popleft()
                total += 1
                flg = True
    checklist = [-1] * (N+1)
    day += 1

if flg:
    print(day)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

N=int(input())
amat=[[-1]]
for i in range(N):
  alist=list(map(int,input().split()))
  amat.append(list(reversed(alist)))
  
#print(amat)
answer=0
matched_flag=[False]*(N+1)
#while(True):  
for answer in range(1,N**3): 
  #answer+=1
  matched_flag=[False]*(N+1)
  unchanged=True
  
  for i in range(1,N+1):
    if len(amat[i]) == 0 or matched_flag[i]:
      continue
      
    ai_next = amat[i][-1]
    if amat[ai_next][-1]==i and not matched_flag[ai_next]:
      #print(i,ai_next,answer)
      amat[i].pop()
      amat[ai_next].pop()
      matched_flag[i]=True
      matched_flag[ai_next]=True
      unchanged=False
  
  if unchanged:
    print(-1)
    sys.exit()
  else:
    maxlist=-1
    for i in range(1,N+1):
      maxlist=max(maxlist,len(amat[i]))
    if maxlist==0:
      print(answer)
      sys.exit()

Submission status: Time Limit Exceeded

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

N=int(input())
A = [list(map(lambda x:int(x)-1,input().split())) for _ in [0]*N]

Ef = {(i,j):[] for i in range(N) for j in range(i+1,N)}
Eb = {(i,j):[] for i in range(N) for j in range(i+1,N)}
for i,B in enumerate(A):
    for a0,a1 in zip(B[:-1],B[1:]):
        k0 = tuple(sorted((i,a0)))
        k1 = tuple(sorted((i,a1)))
        Ef[k0].append(k1)
        Eb[k1].append(k0)
Ef = {k:set(v) for k,v in Ef.items()}
Eb = {k:set(v) for k,v in Eb.items()}

q = [k for k in Eb if Eb[k] == set()]
ans = 0
rmv = 0
while q:
    qq = set()
    for k in q:
        for k2 in Ef[k]:
            Eb[k2].remove(k)
            rmv += 1
            if not Eb[k2] : qq.add(k2)
        Ef[k] = set()
    ans += 1
    q = qq
if rmv != N*(N-2) : ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
r=[]
a=[]
b=[]
for i in range(n):
  r.append([int(i) for i in input().split()])
for i in range(n*(n-1)//2):
  k=[]
  f=[]
  for j in range(n):
    if len(r[j])!=0:
      p=r[j][0]-1
      if r[p][0]==j+1:
        if j+1 not in f:
          if p+1 not in f:
            k.append([r[j].pop(0),r[p].pop(0)])
            f.append(j+1)
            f.append(p+1)
  if len(k)==0:
    break
  else:
    for o in k:
      a.append(o)
    b.append(k)
if len(a)==(n*(n-1)//2):
  print(len(b))
else:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
n=int(input())
a=[[]]
for i in range(n):
    ai = list(map(int,input().split()))
    a.append(ai)
ans=0
while(True):
    empty_lists=0
    battled_i=[]
    for i in range(1,len(a)):
        if(len(a[i]) == 0):
            empty_lists+=1
            continue

        next_i = a[i][0]

        if(i in battled_i or next_i in battled_i):
            continue

        if(a[next_i][0] == i):
            del a[i][0]
            del a[next_i][0]
            battled_i.append(i)
            battled_i.append(next_i)

    if(empty_lists == n):
        break
    elif(len(battled_i) == 0):
        print(-1)
        sys.exit()
    ans+=1
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools, os, pdb
sys.setrecursionlimit(10**7)
from fractions import Fraction
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 [int(x) for x in sys.stdin.readline().split()]
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 _pf(s): return print(s, flush=True)
def perr(s): return print(s, file=sys.stderr)

def main():
    A_list = []
    if 'LOCAL' in os.environ:
        N = 1000
        for i in range(N):
            tmp = [j for j in range(N) if i != j]
            random.shuffle(tmp)
            A_list.append(tmp)

    else:
        N = _I()
        for i in range(N):
            A_list.append(LI())
        #  perr(A_list)
    new_A_list = {}
    for aidx, A in enumerate(A_list):
        new_A_list[aidx] = [i-1 for i in A]
    A_list = new_A_list

    """
    まず、N=1000までなので、
    1000*1000=10**6まである。
    試合の日数を最小かする。
    つまりできるだけ効率よく1日に試合を詰め込むことを考える
    そもそも1のところに2とあったら、
    全通りを求めると？
    どの試合にするかで1000*999/2の階乗=10**6/2の階乗通りある
    まず選手iの1つ目を見ていく
    その相手のところをみて、current_idxがiだったら試合可能

    """

    current_opponent_idx = None
    current_day = 0
    is_ok = False
    # 各選手の試合状況
    current_position_list = [0 for i in range(N)]
    done_player_list = []
    position_sum = 0
    done_sum = (N-1)*N
    all_done_players = []
    while True:
        #  print('day: ', current_day)
        #  print('current position list', current_position_list)
        #  pdb.set_trace()
        is_ok = False
        #  if all(position == N-1 for position in current_position_list):
        if position_sum == done_sum:
            # 全試合終了
            break

        for i in range(N):
            #  print('--- in for---- current position list', current_position_list)
            # 選手iが試合できるか見る
            if i in done_player_list:
                continue

            if i in all_done_players:
                # この選手はすべての試合を終了している
                continue

            # iの試合相手のidx
            opponent_idx = A_list[i][current_position_list[i]]
            if opponent_idx in done_player_list:
                # 試合相手がすでに今日試合してた場合
                continue

            #  print('i', i)
            #  print('opponent', opponent_idx)

            # iの試合相手の次の相手が選手iなら成立する
            if A_list[opponent_idx][current_position_list[opponent_idx]] == i:
                #  print('試合した', i, opponent_idx)
                # 試合可能
                #  done_player_list.extend([i, opponent_idx])
                done_player_list.append(opponent_idx)
                done_player_list.append(i)
                current_position_list[i] += 1
                current_position_list[opponent_idx] += 1
                if current_position_list[i] == N-1:
                    all_done_players.append(i)
                if current_position_list[opponent_idx] == N-1:
                    all_done_players.append(opponent_idx)
                position_sum += 2
                # 試合がまだ可能であるというフラグをつける
                is_ok = True

        if not is_ok:
            # 1試合も成立しなかったらストップする
            print(-1)
            exit()

        done_player_list = []
        current_day += 1

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

Submission status: Time Limit Exceeded

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
    while True:
        used = set()
        for i in range(N):
            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
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# e
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
game = [0]*n
day = [0]*n
cnt = 0
pre = 0
M = n*(n-1)//2
ok = True
while cnt < M:
    for i in range(n):
        if cnt == M:
            break
        if game[i] != n-1:
            opp = a[i][game[i]]-1
            if a[opp][game[opp]]-1 == i:
                cnt += 1
                game[i] += 1
                game[opp] += 1
                mday = max(day[i]+1, day[opp]+1)
                day[i] = day[opp] = mday
    if cnt == pre:
        ok = False
        break
    else:
        pre = cnt
if ok:
    print(max(day))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

import sys
input = sys.stdin.readline


n = int(input())
a_list = [None for _ in range(n)]
num = 0
day = 0
for i in range(n):
    a_list[i] = deque([int(i) - 1 for i in input().split()])

for kkk in range(n * (n - 1) // 2):
    visit = set([])
    day += 1
    for j in range(n):
        if j not in visit:
            if len(a_list[j]) > 0:
                k = a_list[j][0]
                if k not in visit:
                    if a_list[k][0] == j:
                        num += 1
                        visit.add(a_list[j].popleft())
                        visit.add(a_list[k].popleft())
    if (len(visit) == 0):
        day = -1
        break
    if num >= n * (n - 1) // 2:
        break
print(day)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import Counter
n = int(sys.stdin.readline())
battle_dict = dict()
cur_stage = Counter([])
new_ls = []
for i in range(n):
    inp = [int(i) for i in sys.stdin.readline().split()]
    battle_dict[i+1] = inp
    new_ls.append(tuple(sorted([i+1, inp[0]])))
cur_stage.update(new_ls)

cnt = 0
while True:
    flg = 0
    for v, c in cur_stage.items():
        if c > 1:
            i, j = v
            if len(battle_dict[i]) > 0:
                battle_dict[i].pop(0)
            if len(battle_dict[j]) > 0:
                battle_dict[j].pop(0)
            cur_stage[v] = 0
            flg = 1
    if flg == 0:
        break
    else:
        cnt += 1
    cur_stage.clear()
    new_ls = []
    for i, j in battle_dict.items():
        if len(j) > 0:
            new_ls.append(tuple(sorted([i, j[0]])))
    cur_stage.update(new_ls)
if len(cur_stage) > 0:
    print(-1)
else:
    print(cnt)

Submission status: Time Limit Exceeded

Solution code:
def solve(N, A):
    days = 0
    n_games = N * (N-1) / 2
    while n_games > 0:
        n_games_today = 0
        has_game_today = [False] * (N+1)
        for i in range(1, N+1):
            if has_game_today[i]:
                continue
            j = A[i][0]
            if j != -1 & A[j][0] == i:
                has_game_today[i] = True
                has_game_today[j] = True
        n_games_today = sum(has_game_today) // 2
        for i in range(1, N+1):
            if has_game_today[i]:
                A[i].pop(0)
        if n_games_today > 0:
            days += 1
            n_games -= n_games_today
        else:
            return -1
    return days


def main():
    N = int(input())
    A = list()
    A.append([])
    for i in range(N):
        a = list(map(int, input().strip().split()))
        a += [-1, ]
        A.append(a)
    print(solve(N, A))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

td = []
ans = 0
execflg = False
while 1:
        for idx, val in enumerate(A):
                if not val:
                        continue
                oppidx = val[0] - 1
                opp = A[val[0] - 1][0]
                if idx in td or oppidx in td:
                        continue
                
                if opp == idx + 1:
                        execflg = True
                        A[idx].pop(0)
                        A[oppidx].pop(0)
                        td.append(idx)
                        td.append(oppidx)
        else:
                if execflg:
                        td.clear()
                        ans += 1
                        execflg = False
                else:
                        for i in A:
                                if not(not i):
                                        print(-1)
                                        exit()
                        print(ans)
                        exit()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [list(map(lambda x:int(x)-1,input().split())) for i in range(N)]
B = [0]*N
S = 0
ans = 0
while True:
    C = [0]*N
    for n in range(N):
        if C[n]==0 and B[n]!=N-1:
            b = A[n][B[n]]
            if C[b]==1: continue
            if A[b][B[b]]==n:
                B[n]+=1
                B[b]+=1
                C[n],C[b]=1,1
    if sum(C)==0:break
    ans +=1
print(ans if sum(B)==N*(N-1) else -1)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

s = []
fight = n * (n-1)

for i in range(n):
  #s.append(list(map(int, input().split())))
  s.append([int(x) for x in input().split()])


ans = 1
count = 0
s_pos = [0 for i in range(n)]

while True:
  do_Flag = []
  flag = False
  for index, x in enumerate(s):
    if s_pos[index] >= n-1:
      continue
    a = x[s_pos[index]] - 1
    b = s[a][s_pos[a]] - 1
    if b == index:
      count += 1
      do_Flag.append(index)
      flag = True
    
  for i in do_Flag:
    s_pos[i] += 1
  
  if flag:
    if count >= fight:
      print(ans)
      break
    ans += 1
  else:
    print(-1)
    break

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**7)
inf=10**20
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 [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n=I()

  l=[]
  for _ in range(n):
    _l=LI()
    _l.reverse()
    l.append(_l)

  c=n*(n-1)
  ans=1
  nagasa=[n-1]*n
  while True:
    m=[0]*n
    _c=c

    for i in range(n)[::-1]:
      if c<=0:
        return ans

      if m[i]!=0:
        continue

      if nagasa[i]!=0:
        a=l[i][-1]-1

        if m[a]!=0:
          continue

        if nagasa[a]!=0:
          if l[a][-1]==i+1:
            l[a].pop()
            l[i].pop()
            m[a]=1
            m[i]=1
            nagasa[a]-=1
            nagasa[i]-=1
            c-=2
          else:
            continue
        else:
          return -1
      else:
        continue
    if _c==c:
      return -1
    ans+=1

  return ans

# main()
print(main())

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def judge_and_count(A_lst, already_played, played_count):
    count = 0
    while np.sum(played_count) < N*(N-1):
        new_play = False
        for i in range(1, N+1):
            if len(A_lst[i]) > 0 and already_played[i] == 0:
                p1 = i
                p2 = A_lst[i][0]
                if len(A_lst[p2]) == 0:
                    return -1
                if already_played[p2] == 1:
                    continue
                if A_lst[p2][0] == p1:
                    already_played[p1] = 1
                    already_played[p2] = 1
                    A_lst[p1].pop(0)
                    A_lst[p2].pop(0)
                    played_count[p1] += 1
                    played_count[p2] += 1
                    new_play = True
        count += 1
        already_played[:] = 0
        if not new_play:
            return -1
    
    return count


N = int(input())

already_played = np.zeros(N+1)
played_count = np.zeros(N+1)

A_lst = [[]]


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


ans = judge_and_count(A_lst, already_played, played_count)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
dp = [0]*n
cnt = 0
L = []
flag = True
for i in range(n):
  T = []
  N = list(map(int,input().split()))
  for j in range(n-1):
    T.append([i+1,N[j]])
  L.append(T)
while dp != [n-1]*n:
  B = [0]*n
  act = 0
  for i in range(n):
    if B[i] != 0:
      None
    else:
      B[i] = 1
      if dp[i] == n-1:
        None
      else:
        miru = L[i][dp[i]][1]
        if dp[miru-1] == n-1:
          flag = False
          break
        else:
          if B[miru-1] != 1:
            sie = dp[miru-1]
            if L[miru-1][sie][1] == i+1:
              dp[i] += 1
              dp[miru-1] += 1
              B[miru-1] = 1
              act += 1
            else:
              None
          else:
              None
  if act == 0:
    dp = [n-1]*n
    flag = False
  cnt += 1
if flag == False:
  print(-1)
else:
  print(cnt)

Submission status: Time Limit Exceeded

Solution code:
def solve():
  import sys

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

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


if __name__ == '__main__':
  solve()

Submission status: Time Limit Exceeded

Solution code:
def seek_candidates(current_A):
    can_set = []
    want_set = []
    for n in range(N):
        if(current_A[n+1] != []):
            tmp = set([n+1, current_A[n+1][0]])
            if tmp in want_set:
                can_set.append(tmp)
            else:
                want_set.append(tmp)
    return can_set

def make_next_A(current_A, battles):
    next_A = collections.Counter(current_A)
    for battle in battles:
        index = list(battle)
        next_A[index[0]] = current_A[index[0]][1:]
        next_A[index[1]] = current_A[index[1]][1:]
    return next_A

def check_A(current_A):
    for n in range(N):
        if(current_A[n+1] != []):
            return False
    return True

def make_battle_set(can_set):
    battle_set = []
    battle_players = set()
    for c in can_set:
        c = list(c)
        if(c[0] not in battle_players and c[1] not in battle_players):
            battle_set.append(c)
            battle_players = battle_players | set(c)
    return battle_set

import collections

A = collections.Counter()
N = int(input())
for n in range(N):
    A[n+1] = list(map(int, input().split()))

success_flag = False
loop_count = 0
currnet_A = A
while(True):
    loop_count += 1
    can_set = seek_candidates(currnet_A)
    if(can_set == []):
        break
    battle_set = make_battle_set(can_set)
    currnet_A = make_next_A(currnet_A, battle_set)
    if(check_A(currnet_A)):
        success_flag = True
        break
if(success_flag):
    print(loop_count)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline


class AtCoder:
    def main(self):
        N = int(input())
        A = [list(map(int, input().split())) for _ in range(N)]

        already_p = set()
        days = 0
        while True:
            f = True
            for a in A:
                if len(a) > 0:
                    f = False
            if f:
                break

            for i in range(N):
                if len(A[i]) == 0:
                    continue
                if i + 1 not in already_p and A[i][0] not in already_p and A[A[i][0] - 1][0] == i + 1:
                    already_p.add(i + 1)
                    already_p.add(A[i][0])
            if len(already_p) == 0:
                print(-1)
                exit()
            for p in already_p:
                A[p - 1] = A[p - 1][1:]

            already_p = set()
            days += 1

        print(days)


if __name__ == '__main__':
    AtCoder().main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
plan=[None]*n
for i in range(n):
  p=list(map(int,input().split()))
  for j in range(len(p)):
    p[j]=p[j]-1
  plan[i]=p
 
d=0
error=False
while True:
  d=d+1
  done=[True]*n
  thisday=False
  for i in range(n):
    if done[i]==False:
      continue
    if len(plan[i])==0:
      continue
    target=plan[i][0]
    if done[target]==False:
      continue
    if len(plan[target])==0:
      continue
    if plan[target][0]==i:
      # match
      plan[i]=plan[i][1:]
      plan[target]=plan[target][1:]
      done[i]=False
      done[target]=False
      thisday=True
  if thisday==False:
    # no game today
    # check if every plan is finished
    for i in range(len(plan)):
      if len(plan[i])!=0:
        error=True
    break
  
if error:
  print(-1)
else:
  print(d-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def p_e():
    N = int(input())
    A = [deque(map(lambda x: x - 1, map(int, input().split()))) for _ in range(N)]

    ans = 0
    while True:
        idx = []
        for i in range(N):
            if not A[i]:
                continue

            if i == A[A[i][0]][0]:
                idx.append(i)

        if not idx:
            break

        for i in idx:
            A[i].popleft()
        ans += 1

    for a in A:
        if a:
            print(-1)
            exit()

    print(ans)


if __name__ == '__main__':
    p_e()

Submission status: Time Limit Exceeded

Solution code:

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

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

    # check = [[True] + [False] * (N - 2) for _ in range(N)] #True準備完了、False試合不可
    check = [0] * N #i番目の次の相手のindex

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n=int(input())
league=[deque(map(int,input().split())) for _ in range(n)]

total_match=n*(n-1)//2
match=0
day=0

for _ in range(total_match):
    day+=1
    today_match=[]

    for i in range(n):
        if i in today_match:
            continue
        if league[i]:
            m=league[i][0]-1
            if m in today_match:
                continue
            if league[m] and league[m][0]-1==i:
                today_match.extend((league[i].popleft()-1, league[m].popleft()-1))
    if not today_match:
        day=-1
        break
    match+=len(today_match)//2
    if match>=total_match:
        break

print(day)

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
a_list = [None for _ in range(n)]
num = 0
day = 0
for i in range(n):
    a_list[i] = deque([int(i) - 1 for i in input().split()])

for kkk in range(n * (n - 1) // 2):
    visit = set([])
    day += 1
    for j in range(n):
        if j not in visit:
            if len(a_list[j]) > 0:
                k = a_list[j][0]
                if k not in visit:
                    if a_list[k][0] == j:
                        num += 1
                        visit.add(a_list[j].popleft())
                        visit.add(a_list[k].popleft())
    if (len(visit) == 0):
        day = -1
        break
    if num >= n * (n - 1) // 2:
        break
print(day)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [[]] + [list(map(int, input().split())) for n in range(N)]
P = [0] * (N + 1)

def get_num(i):
    if P[i] >= N - 1:
        return -1
    return A[i][P[i]]


def update(mem):
    for i in mem:
        P[i] += 1


def f():
    mem = set()
    for t in range(N * (N - 1) // 2 + 1):
        if P.count(N - 1) == N:
            return t

        for i in range(1, N + 1):
            if i in mem:
                continue

            j = get_num(i)
            if i == get_num(j):
                mem.add(i)
                mem.add(j)

        if len(mem) == 0:
            return -1

        update(mem)
        mem = set()

    return -2

print(f())