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:
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*(n-1)
  
  while sum(c) < m:
    candidate = set()
    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.add(i)
        candidate.add(j)

    if candidate:
      for i in candidate:
        c[i]+=1
      d+=1
    else:
      d=-1
      break
      
  print(d)


if __name__ == '__main__':
  solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
A = []
for i in range(N):
    A.append(list(map(int, input().split())))
index = [0]*(N+1)

for k in range(600000):
    today = [True]*(N+1)
    flag = 0
    for j in range(N):
        if not today[j+1]:
            continue
        if index[j+1] >= N-1:
            continue
        opponent = A[j][index[j+1]]
        if A[opponent-1][index[opponent]] == j+1:
            if today[opponent]:
                index[opponent] += 1
                index[j+1] += 1
                today[opponent] = False
                today[j+1] = False
                flag = 1
    if flag == 0:
        if sum(index) == N*(N-1):
            ans = k
            break
        else:
            ans = -1
            break

print(ans)

Submission status: Time Limit Exceeded

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

output = 0
memo = [0] * N
newmemo = [0] * N
owari = [0] * N
flag = 0
while flag < N:
    ng = 0
    i = 0
    while i < N:
        check = A[i][memo[i]]-1
        if i==A[check][memo[check]]-1:
            if memo[i] < N-2:
                newmemo[i]+=1
            elif (memo[i] == N-2) and (owari[i]==0):
                owari[i] = 1
                flag += 1
            elif (memo[i] == N-2) and (owari[i]==1):
                continue
        else:
            ng += 1
        i+=1
    if ng == N:
        output = -1
        break
    memo = newmemo[:]
    output += 1

print(output)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
def solve():
    N = int(input())
    A = {j:iter(map(int, input().split())) for j in range(1,N+1)}
    res = 0
    B_ = {j:next(A[j]) for j in A}
    while A:
        B = B_.copy()
        checked = False
        for j in B_:
            if B_[B_[j]] == j:
                try:
                    B[j] = next(A[j])
                except StopIteration:
                    A.pop(j)
                    B.pop(j)
                checked = True
        if checked:
            res += 1
            B_ = B
        elif B:
            res = -1
            break

    return str(res)

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [0] * (n+1)
for i in range(n):
    a[i+1] = tuple(map(int, input().split()))
todo = [0] * (n+1)
days = 0
while True:
    update = []
    for i in range(1, n+1):
        if todo[i] < n - 1 and i not in update:
            p = a[i][todo[i]]
            if a[p][todo[p]] == i:
                update.append(i)
    for j in update:
        todo[j] += 1
    days += 1
    #print(todo)
    if update == []:
        days = -1
        break
    elif todo[1:] == [n - 1] * n:
        break
print(days)

Submission status: Time Limit Exceeded

Solution code:
def main():
  from sys import exit
  n = int(input())
  a = [list(map(int, input().split())) for _ in range(n)]
  ilist = [0] * n
  days = 1
  finished = 0
  while True:
    booked = [False] * n
    books = 0
    for i in range(n):
      if booked[i]:
        continue
      ii = ilist[i]
      if ii == n - 1:
        continue
      j = a[i][ii] - 1
      if booked[j]:
        continue
      if a[j][ilist[j]] - 1 != i:
        continue
      books += 1
      booked[i] = True
      booked[j] = True
      ilist[i] += 1
      if ilist[i] == n -1:
        finished += 1
      ilist[j] += 1
      if ilist[j] == n -1:
        finished += 1
    if books == 0:
      print(-1)
      exit()
    if finished == n:
      break
    days += 1
  print(days)
main()

Submission status: Time Limit Exceeded

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

N = int(input())
A = [0]*N

for i in range(N):
    X = list(map(int,input().split()))
    X = deque([[i+1,X[j]] for j in range(N-1)])
    A[i] = X

res = 0
cnt = 0
pcnt = [N-1]*N
while 1:
    prev = cnt
    flag = [0]*N
    for i in range(N):
        if flag[i] == 0 and pcnt[i] != 0:
            X = A[i][0]
            ind = X[1]-1
            if pcnt[ind] != 0:
                if A[ind][0] == X[::-1] and flag[ind] == 0:
                    A[i].popleft()
                    A[ind].popleft()
                    flag[i] = 1
                    flag[ind] = 1
                    cnt += 1
                    pcnt[i] -= 1
                    pcnt[ind] -= 1
    if cnt == prev:
        res = -1
        break
    else:
        res += 1
        if cnt == N*(N-1)//2:
            break
print(res)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

def main():
	N = inputInt()
	A = []
	for i in range(N):
		tmp = inputList()
		A.append(tmp)

	ind = [0] * N
	ans = 0

	anfl = True

	for i in range(80000):
		flg = False
		doList = []

		for i, val in enumerate(ind):
			if val == -1:
				continue

			min = A[i]
			target = min[val]

			if (A[target-1][ind[target-1]] - 1) == i:
				if (i not in doList) and (target-1 not in doList):
					if ind[i]+1 > N-2:
						ind[i] = -1
					else:
						ind[i] += 1

					if ind[target-1]+1 > N-2:
						ind[target-1] = -1
					else:
						ind[target-1] += 1

					doList.append(i)
					doList.append(target-1)
					flg = True

		if flg == True:
			ans += 1
		else:
			anfl = False
			break

	if anfl == False:
		for i in ind:
			if i != -1:
				print(-1)
				sys.exit()

		print(ans)
	else:
		print((N*(N-1))/2)



if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

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

n = int(input())

match = n * (n - 1) // 2
remain = [n - 1] * n
day = 0
waiting = []
finished = 0
for i in range(n):
    waiting.append(list(map(int, input().split())))

while match != 0:
    ml = [0] * n
    for i, wait_l in enumerate(waiting):
        if remain[i] == 0 or remain[wait_l[0] - 1] == 0:
            continue
        if ml[i] == 0 and ml[wait_l[0] - 1] == 0:
            if (i + 1) == waiting[wait_l[0] - 1][0]:
                ml[i] = 1
                ml[wait_l[0] - 1] = 1
                if remain[i] != 1:
                    waiting[i] = waiting[i][1:]
                    remain[i] -= 1
                else:
                    waiting[i] = []
                    finished += 1
                    remain[i] -= 1
                if remain[wait_l[0] - 1] != 1:
                    waiting[wait_l[0] - 1] = waiting[wait_l[0] - 1][1:]
                    remain[wait_l[0] - 1] -= 1
                else:
                    waiting[wait_l[0] - 1] = []
                    finished += 1
                    remain[wait_l[0] - 1] -= 1
                match -= 1
    if 1 in ml:
        day += 1
        if finished == n:
            print(day)
            exit()
    else:
        print("-1")
        exit()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
H = [0]*N
A = [0]*N
A2 = [0]*N
flag=0
flag2=0
for i in range(N):
    H[i] = list(map(int, input().split()))

k=0
while(True):
    k+=1
    for i in range(N):
        if(A[i]==0):
            if(A[H[i][0]-1]==0):
                if(H[H[i][0]-1][0]==i+1):
                    A[i]=1
                    A[H[i][0]-1]=1
                    if(len(H[H[i][0]-1])==1):
                        A2[H[i][0]-1]=1
                    if(len(H[i])==1):
                        A2[i]=1

                    H[H[i][0]-1].pop(0)
                    H[i].pop(0)
                    
                    flag2=0

    for j in range(N):
        A[j] = A2[j]
        if(A2[j]==0):
            flag=0
    
    if(flag==1):
        break
    if(flag2==1):
        break
    
    flag=1
    flag2=1

if(flag2==1):
    print("-1")
    exit()

print(k)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n=int(input())
al=[deque(map(int,input().split())) for _ in range(n)]
m=n*(n-1)//2
tn=[n-1]*n
for i in range(m+1):
    flg=True
    s=0
    ts=set()
    for j in range(n):
        if tn[j]>0 and j not in ts:
            t=al[j][0]-1
            if t not in ts:
                if al[t][0]==j+1:
                    al[t].popleft()
                    tn[t]-=1
                    ts.add(t)
                    al[j].popleft()
                    tn[j]-=1
                    flg=False
        ts.add(j)
        s+=tn[j]
    if s==0:
        print(i+1)
        exit()
    if flg:
        print(-1)
        exit()

Submission status: Time Limit Exceeded

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


def main():
    N = int(input())
    op = [[]]
    for i in range(N):
        op.append(deque(list(map(int, input().split()))))

    day = 0
    ok = 1
    count = (N * (N - 1)) // 2
    can = 1
    while True:
        if not ok:
            day = -1
            print('ok')
            break
        if count == 0:
            break
        if can == 0:
            day = -1
            break
        played = [0] * (N + 1)
        k = 1
        k_seen = 1
        end_day = 0
        can = 0
        while True:
            if len(op[k]) > 0:
                opponent = op[k][0]
                if len(op[opponent]) > 0:
                    if op[opponent][0] == k:
                        if played[k] == 0 and played[opponent] == 0:
                            count -= 1
                            can = 1
                            op[k].popleft()
                            op[opponent].popleft()
                        played[k] = 1
                        played[opponent] = 1
                        k_seen += 1
                        k = k_seen
                        while played[k] == 1:
                            k += 1
                            if k == N + 1:
                                day += 1
                                end_day = 1
                                break
                    else:
                        played[k] = 1
                        if played[opponent] == 0:
                            k = opponent
                        else:
                            k_seen += 1
                            k = k_seen
                            while played[k] == 1:
                                k += 1
                                if k == N + 1:
                                    day += 1
                                    end_day = 1
                                    break
                else:
                    ok = 0
                    break
            else:
                played[k] = 1
                k_seen += 1
                k = k_seen
                while played[k] == 1:
                    k += 1
                    if k == N + 1:
                        day += 1
                        end_day = 1
                        break
            if end_day == 1:
                break

    print(day)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python

import sys
from collections import deque

n= int(sys.stdin.readline())
a= [ None for _ in range(n) ]
for i in range(n):
    a[i]= deque( [ int(x)-1 for x in sys.stdin.readline().split() ] )
#
tot= (n*(n-1))//2
now= 0
c= 0
flags= [ False for _ in range(n) ]
for _ in range(tot):
    for i in range(n):
        if flags[i]: continue
        ai = a[i]
        if not ai: continue
        j  = ai[0]
        if j<i: continue
        aj = a[j]
        if aj[0]==i:
            flags[i]= True
            flags[j]= True
            now+= 1
    #
    if not any(flags): break
    for i in range(n):
        if flags[i]:
            flags[i]= False
            a[i].popleft()
    #
    c+= 1
    if now==tot: break
#
if now==tot: print( c )
else: print( -1 )

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
A = [[0] * (N-1)]+[list(map(int,input().split())) for _ in range(N)]

idx = [0] * (N+1)
cnt = 0
day = 0
flag_max = [False] * (N+1)
while cnt != N:
    
    error = True
    flag =[False] * (N+1)
    looplist = [i for i in range(1,N+1) if not(flag_max[i])]
    
    for i in looplist:
        if (flag[i]):continue
        tmp = A[i][idx[i]]
        if (flag[tmp]):continue
    
        if A[tmp][idx[tmp]] == i:
            idx[tmp] = idx[tmp] + 1
            idx[i] = idx[i] + 1
            if idx[tmp] == N-1:
                flag_max[tmp] = True
                cnt += 1
            if idx[i] == N-1:
                flag_max[i] = True
                cnt += 1
            flag[i] = True
            flag[tmp] = True
            error = False
    if error:
        print(-1)
        sys.exit()
    
    day += 1
            

    if day > 50000:
        print(N*(N-1)//2)
    
    
print(day)

Submission status: Time Limit Exceeded

Solution code:
n1 = int(input())

n2 = []

for i1 in range(n1):
    n2.append([int(i) for i in input().split()])

n3 = [0] * n1
r1 = 0

for i2 in range(500000):
    r1 += 1
    d1 = {}
    for i3 in range(n1 - 1):
        if n3[i3] >= n1 - 1:
            continue
        t2 = n2[i3][n3[i3]] - 1
        if n2[t2][n3[t2]] == (i3 + 1) and i3 < t2 and d1.get(i3, 0) == 0 and d1.get(t2, 0) == 0:
            n3[i3] += 1
            n3[t2] += 1
            d1[i3] = 1
            d1[t2] = 1

    if min(n3) >= (n1 - 1):
        break
    if len(d1) == 0:
        r1 = -1
        break

print(r1)

Submission status: Time Limit Exceeded

Solution code:
import sys


def input(): return sys.stdin.readline().strip()


def main():
    N = int(input())
    A = [[]]
    for _ in range(N):
        a = map(int, input().split())
        a = reversed(list(a))
        A.append(list(a))

    days = 0
    while any(A):
        changed = False
        matched = [False] * (N+1)
        for i in range(1, N+1):
            if matched[i] or len(A[i]) == 0:
                continue

            player1 = A[i][-1]

            for j in range(i+1, N+1):
                if matched[j] or len(A[j]) == 0:
                    continue

                player2 = A[j][-1]

                if player1 == j and player2 == i:
                    A[i].pop()
                    A[j].pop()
                    matched[i] = True
                    matched[j] = True
                    changed = True
                    break

        if not changed:
            print(-1)
            return

        days += 1

    print(days)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

order=[0]*n

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

    for i in range(n):
        try:
            m=league[i][order[i]]-1
            if not i in today_match and not m in today_match:
                if league[m][order[m]]-1==i:
                    today_match.extend((i,m))
                    order[i]+=1
                    order[m]+=1
        except:
            continue
    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:
import sys
input = sys.stdin.readline

N = int(input())
A = [[int(i) - 1 for i in input().split()] for _ in range(N)]

cur = [0] * N

max_pairs = N * (N - 1)

pairs = 0
cnt = 1
while True:
    visited = [False] * N
    for i, a in enumerate(A):
        if cur[i] >= N - 1:
            continue
        p = a[cur[i]]
        if A[p][cur[p]] == i:
            # print(cnt, p + 1, A[p][cur[p]] + 1, i + 1)
            visited[i] = True
            visited[a[cur[i]]] = True
            pairs += 1

    # print(pairs)
    if pairs == max_pairs:
        break
    if pairs > max_pairs:
        print(-1)
        quit()

    update = False
    for i, v in enumerate(visited):
        if v:
            cur[i] += 1
            update = True

    if not update:
        print(-1)
        quit()

    cnt += 1

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
fin = [False] * N
An = [''] * N
deg = [0] * N
for n in range(N):
    An[n] = [int(x) for x in input().split()]

days = 0
while False in fin:
    days += 1
    matched = [False] * N
    flag = False
    for n in [n for n in range(N-1) if fin[n]==False]:
        if matched[n]:
            continue
        op = An[n][deg[n]] - 1
        if matched[op]:
            continue
        if An[op][deg[op]] == n + 1:
            flag = True
            matched[n] = True
            matched[op] = True
            deg[n] += 1
            deg[op] += 1
            if deg[n] == N - 1:
                fin[n] = True
            if deg[op] == N - 1:
                fin[op] = True
    if not flag:
        days = -1
        break
print(days)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
dic = {}
for i in range(N):
  a = [int(i) for i in input().split()]
  dic[i+1] = a[::-1]
count = 0
while True:
  nokori = 0
  flag = True
  log = [-1]*N
  for k in dic.keys():
    k = int(k)
    if dic[k]==[]:
      nokori += 1
      continue
    p2 = dic[k][-1]
#    print(k,p2)
    if log[p2-1]==1:
      continue
    if dic[p2]==[]:
      print(-1)
      break
    if dic[p2][-1]==k and log[k-1]==-1 and log[p2-1]==-1:
      a = dic[k].pop()
      b = dic[p2].pop()
#      print('%', a,b)
      log[k-1] = 1
      log[p2-1] = 1
      flag = False
      
  if nokori == N:
    print(count)
    break
  count += 1
  if flag:
    print(-1)
    break

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

def main():
	N = inputInt()
	A = []
	for i in range(N):
		tmp = inputList()
		A.append(tmp)

	ind = [0] * N
	ans = 0

	anfl = True

	for i in range(90000):
		flg = False
		doList = []

		for i, val in enumerate(ind):
			if val == -1:
				continue

			min = A[i]
			target = min[val]

			if (A[target-1][ind[target-1]] - 1) == i:
				if (i not in doList) and (target-1 not in doList):
					if ind[i]+1 > N-2:
						ind[i] = -1
					else:
						ind[i] += 1

					if ind[target-1]+1 > N-2:
						ind[target-1] = -1
					else:
						ind[target-1] += 1

					doList.append(i)
					doList.append(target-1)
					flg = True

		if flg == True:
			ans += 1
		else:
			anfl = False
			break

	if anfl == False:
		for i in ind:
			if i != -1:
				print(-1)
				sys.exit()

		print(ans)
	else:
		print((N*(N-1))/2)



if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
from collections import deque

def main():
	n = int(input().strip())
	dqlist = [0] * (n+1)
	for i in range(n):
		v = list(map(int, input().strip().split()))
		dqlist[i+1] = deque(v)
	day = 0
	zeroc = 0
	while True:
		picked = [0] * (n+1)
		changed = False
		for i in range(1, n+1):
			if picked[i] == 1:
				continue
			if len(dqlist[i]) == 0:
				continue
			if dqlist[dqlist[i][0]][0] == i:
				if picked[dqlist[i][0]] == 1:
					continue
				# OK
				changed = True
				c = dqlist[i].popleft()
				dqlist[c].popleft()
				picked[i] = 1
				picked[c] = 1
				if len(dqlist[i]) == 0:
					zeroc += 1
				if len(dqlist[c]) == 0:
					zeroc += 1
		if changed == False:
			if zeroc == n:
				print(day)
				return
			else:
				print(-1)
				return
		day += 1

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

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

flag2 = 0
flag3 = 0
n = 0
while(1):
    n = n + 1
    tmp_list = []
    flag = 0
    for i in l:
        if (i != []):
            flag = 1
    if flag == 1:
        if (flag2 == 1):
            if (flag3 == 1):
                break
            flag3 = 1
            continue
        flag2 = 1
        for i in range(N):
            if l[i] == []:
                continue
            t = l[i][0]
            if not((i+1 in tmp_list) or (t in tmp_list)):
                if (l[t-1][0]==i+1):
                    tmp_list.append(i+1)
                    tmp_list.append(t)
                    l[i]=l[i][1:]
                    l[t-1]=l[t-1][1:]
                    flag2 = 0
                    flag3 = 1
    else :
        flag3 = 0
        break
if flag3 == 1:
    print(-1)
else:
    print(n-1)

Submission status: Time Limit Exceeded

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

cnt = 0
eCount = n * (n-1)
while True :
    rmv = set()
    #print(a)
    for i in range(len(a)) :
        if len(a[i]) == 0 :
            continue
        index = a[i][0] - 1
        #print(i, index)
        if a[index][0] == i + 1:
            #print('koko')
            #print(index, i)
            rmv.add(index)
            rmv.add(i)
    if len(rmv) == 0 :
        print(-1)
        exit()
    #print(a, rmv)
    for elem in rmv :
        a[elem].pop(0)
        eCount -= 1
    #print(a)
    cnt += 1
    if eCount == 0 :
        break

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [list(map(int, input().split())) for _ in range(N)]
l = [0] * N
ans = 0
count = 0
check = [False] * N

while(count <= N - 1):
    check = [False] * N
    for i in range(N):
        if l[i] < N - 1:
            to = A[i][l[i]] - 1
            if (not check[to]) and (not check[i]):
                if A[to][l[to]] - 1 == i:
                    l[i] += 1
                    l[to] += 1
                    check[to] = True
                    check[i] = True
                if l[i] == N - 1:
                    count += 1
                if l[to] == N - 1:
                    count += 1
    ans += 1
    if ans > N ** 2:
        print(-1)
        exit()
    # print(l, ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    import sys
    input = sys.stdin.readline

    n = int(input())
    L = [deque(map(lambda x: int(x) - 1, input().split())) for _ in range(n)]

    ans = 0
    count = 0
    MAX_COUNT = n * (n-1)
    iteration_times = 0
    flag = 0

    while iteration_times <= MAX_COUNT:
        # print(L)
        # print(count)
        iteration_times += 1

        if count == MAX_COUNT:
            flag = 1
            break
        
        numset = set()
        add = numset.add
        flag = 100
        for i in range(n):
            if len(L[i]) != 0:
                a = L[i][0]
                b = L[a][0]
                if i == b:
                    add(i)
                    add(b)
                    flag = 0
        
        if flag == 100:
            break
        for elm in numset:
            L[elm].popleft()
            count += 1

        ans += 1

    if flag == 1:
        print(ans)
    else:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
li = deque(list(map(int,input().split())) for i in range(1,n+1))

cnt = 0
check = []
play = 0
tamel = []
s = 0

while play < n*(n-1) // 2:
    s = play
    for i in range(1,n):
        if i in check or len(li[i-1]) == 0:
            continue
        temp = li[i-1][0]
        if temp <= i:
            continue
        if li[temp-1][0] == i and temp not in check:
            del li[i-1][0]
            del li[temp-1][0]
            play += 1
            check.append(temp)
    cnt += 1
    tamel = []
    check = []
    
    if s == play:
        print(-1)
        exit()

print(cnt)

Submission status: Time Limit Exceeded

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

n = int(input())
game = {}

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

count = 0
final = n*(n-1)//2
for day in range(1, 1000000):
    finish = [0]*(n+1)
    possible = False
    for me in range(1, n+1):
        if finish[me] == 1 or game[me] == deque([]):
            continue

        you = game[me][0]
        if finish[you] == 1 or game[you] == deque([]):
            continue
        else:
            if game[you][0] == me:
                finish[game[you].popleft()] = 1
                finish[game[me].popleft()] = 1
                possible = True
                count += 1
            else:
                continue

    if not possible:
        print(-1)
        exit()

    if count == final:
        print(day)
        exit()

Submission status: Time Limit Exceeded

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

from collections import deque

N = int(input())

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

ans = 0

len_count = [0]*N
lencount=0
while lencount < N:
    update = False
    done = [0]*(N)
    for i in range(N):
        if done[i] == 1: continue
        if len(A[i]) == 0: continue
        tmp = A[i][0]-1
        if done[tmp] == 1: continue
        if len(A[tmp]) !=0 and A[tmp][0]-1 == i:
            update = True
            done[i] = 1
            done[tmp] = 1
            A[i].popleft()
            A[tmp].popleft()
            if len(A[i])==0 and len_count[i]==0:
                len_count[i] = 1
                lencount+=1
            if len(A[tmp])==0 and len_count[tmp]==0:
                len_count[tmp] = 1
                lencount+=1
    #print(lencount)
    if not(update):
        print(-1)
        sys.exit()
    ans+=1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    n = int(input())
    am = []
 
    from collections import deque
 
    for i in range(n):
        am.append(deque(list(map(lambda x: int(x) - 1, input().split()))))
 
    cnt = n * (n - 1) // 2
 
    day = 0
    while cnt > 0:
        day += 1
        match = 0
        done = {}
        for i in range(n):
            if i in done:
                continue
            if len(am[i]) == 0:
                continue
            j = am[i][0]
            if j not in done and am[j][0] == i:
                am[i].popleft()
                am[j].popleft()
                done[i] = 1
                done[j] = 1
                match += 1
 
        if match == 0:
            print(-1)
            return
        else:
            cnt -= match
 
    print(day)
    
resolve()

Submission status: Time Limit Exceeded

Solution code:
def getlist():
	return list(map(int, input().split()))

X = []
N = int(input())
for i in range(N):
	A = getlist()
	A.reverse()
	X.append([0] + A)

#日数
day = 0
while True:
	j = "No"
	check = [0] * N
	for i in range(N):
		x = X[i][-1] - 1
		if x != -1:
			if check[i] == 0 and check[x] == 0 and X[x][-1] == i + 1:
				check[i] = 1
				check[x] = 1
				X[x].pop(-1)
				X[i].pop(-1)
				j = "Yes"
	day += 1
	if j == "No":
		break

#判定
cc = "Yes"
for i in range(N):
	if X[i] != [0]:
		cc = "No"
		break

if cc == "No":
	print(-1)
else:
	print(day - 1)