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 main():
    import sys
    input = sys.stdin.buffer.readline
    N = int(input())
    c = [[int(i)-1 for i in input().split()] for j in range(N)]
    from collections import defaultdict
    edge = defaultdict(set)
    deg = defaultdict(int)
    for i, A in enumerate(c):
        for j in range(N-2):
            if i < A[j]:
                if i < A[j+1]:
                    edge[(i, A[j])].add((i, A[j+1]))
                    deg[(i, A[j+1])] += 1
                else:
                    edge[(i, A[j])].add((A[j+1], i))
                    deg[(A[j+1], i)] += 1
            else:
                if i < A[j+1]:
                    edge[(A[j], i)].add((i, A[j+1]))
                    deg[(i, A[j+1])] += 1
                else:
                    edge[(A[j], i)].add((A[j+1], i))
                    deg[(A[j+1], i)] += 1

    from collections import deque
    que = deque()
    dist = defaultdict(int)
    for i in range(N):
        for j in range(i+1, N):
            if deg[(i, j)] == 0:
                que.append((i, j))  # root
                dist[(i, j)] = 1
    while que:
        u = que.popleft()
        for v in edge[u]:
            deg[v] -= 1
            dist[v] = max(dist[v], dist[u] + 1)
            if deg[v] == 0:
                que.append(v)

    if any(deg.values()):
        # 閉路検出
        print(-1)
    else:
        print(max(dist.values()))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
INF=10**18
def input():
    return sys.stdin.readline().rstrip()

def main():
    N=int(input())
    d={}
    c=0
    edge1=[[] for _ in range(N*(N-1)//2)]
    edge2=[[] for _ in range(N*(N-1)//2)]
    for i in range(N):
        l=list(map(lambda x: int(x)-1,input().split()))
        prev=-1
        for x in l:
            a=min(i,x)*10**3+max(i,x)
            if a in d:
                z=d[a]
                if prev!=-1:
                    edge1[prev].append(z)
                    edge2[z].append(prev)
                prev=z
            else:
                d[a]=c
                if prev!=-1:
                    edge1[prev].append(c)
                    edge2[c].append(prev)
                c+=1
                prev=d[a]
    stack=[]
    days=[-1]*(N*(N-1)//2)
    for i,l in enumerate(edge2):
        if not l:
            stack.append(i)
            days[i]=1
    while stack:
        v=stack.pop()
        for x in edge1[v]:
            days[x]=max(days[x],days[v]+1)
            stack.append(x)
    print(max(days))
        

    

        
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    N = int(input())
    from collections import defaultdict
    edge = defaultdict(set)
    deg = defaultdict(int)
    for i in range(N):
        A = [int(k)-1 for k in input().split()]
        for j in range(N-2):
            if i < A[j]:
                if i < A[j+1]:
                    edge[(i, A[j])].add((i, A[j+1]))
                    deg[(i, A[j+1])] += 1
                else:
                    edge[(i, A[j])].add((A[j+1], i))
                    deg[(A[j+1], i)] += 1
            else:
                if i < A[j+1]:
                    edge[(A[j], i)].add((i, A[j+1]))
                    deg[(i, A[j+1])] += 1
                else:
                    edge[(A[j], i)].add((A[j+1], i))
                    deg[(A[j+1], i)] += 1

    from collections import deque
    que = deque()
    order = 1
    ans = []
    dist = defaultdict(int)
    for i in range(N):
        for j in range(i+1, N):
            if deg[(i, j)] == 0:
                que.append((i, j))  # root
                ans.append(((i, j), order))
                dist[(i, j)] = 1
                order += 1
    while que:
        u = que.popleft()
        for v in edge[u]:
            deg[v] -= 1
            dist[v] = max(dist[v], dist[u] + 1)
            if deg[v] == 0:
                que.append(v)
                ans.append((v, order))
                order += 1

    if len(ans) != N*(N-1)//2:
        return print(-1)

    print(max(dist.values()))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    N = int(input())
    A = dict()
    for i in range(N): A[i] = deque(map(int, input().split()))
    days = 0
    while A:
        this_day = set()
        fin = set()
        days += 1
        for i in A:
            if i in this_day: continue
            else:
                a = A[i].popleft()
                if a - 1 not in this_day:
                    b = A[a-1].popleft()
                    if i == b - 1: 
                        this_day |= {i, a-1}
                        if not A[i]: fin |= {i}
                        if not A[a-1]: fin |= {a-1}
                    else:
                        A[i].appendleft(a)
                        A[a-1].appendleft(b) 
                else: A[i].appendleft(a)
        if not this_day:
            print(-1)
            break
        else:
            for key in fin: del A[key]
    else: print(days)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    N = int(input())
    A = [deque(map(int, input().split())) for _ in range(N)]
    Fin = [False] * N
    days = 0
    while False in Fin:
        this_day = set()
        days += 1
        for i in range(N):
            if Fin[i] or i in this_day: continue
            else:
                a = A[i].popleft()
                if a - 1 not in this_day:
                    b = A[a-1].popleft()
                    if i == b - 1: 
                        this_day |= {i, a-1}
                        if not A[i]: Fin[i] = True
                        if not A[a-1]: Fin[a-1] = True
                    else:
                        A[i].appendleft(a)
                        A[a-1].appendleft(b) 
                else: A[i].appendleft(a)
        if not this_day:
            print(-1)
            break
    else: print(days)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

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

N = int(input())
A = [None] + [list(map(int, input().split()))[::-1] for _ in range(N)]
ans = 0
while any(A):
    used = set()
    for i in range(1, N+1):
        if not A[i] or i in used:
            continue
        j = A[i][-1]
        if j in used:
            continue
        if A[j][-1] == i:
            used.add(i)
            used.add(j)
            A[i].pop()
            A[j].pop()
    if not used:
        ans = -1
        break
    ans += 1
print(ans)

Submission status: Time Limit Exceeded

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

N = int(input())
A = [None] + [deque(map(int, input().split())) for _ in range(N)]
ans = 0
while any(A):
    used = set()
    for i in range(1, N+1):
        if not A[i] or i in used:
            continue
        j = A[i][0]
        if j in used:
            continue
        if A[j][0] == i:
            used.add(i)
            used.add(j)
            A[i].popleft()
            A[j].popleft()
    if not used:
        ans = -1
        break
    ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
"""from collections import *
from itertools import *
from bisect import *
from heapq import *

import math
from fractions import gcd"""
import copy
N=int(input())
A=[list(reversed(list(map(int,input().split())))) for i in range(N)]
for i in range(N):
    for m in range(N-1):
        A[i][m]-=1

playerlst=set([i for i in range(N)])

count=0
nlst=copy.copy(playerlst)
while playerlst:
    flag=0
    lst=copy.copy(playerlst)
    playedlst=set()
    while nlst:
        p=nlst.pop()
        if p in lst:
            p2=A[p][-1]
            if p2 in lst and A[p2][-1]==p:
                flag=1
                A[p].pop()
                A[p2].pop()
                lst.remove(p)
                lst.remove(p2)
                if p2 in nlst:
                    nlst.remove(p2)
                playedlst.add(p)
                playedlst.add(p2)
                if not A[p]:
                    playerlst.remove(p)
                if not A[p2]:
                    playerlst.remove(p2)
    if not flag:
        print(-1)
        exit()
    count+=1
    nlst=copy.copy(playedlst)
print(count)

Submission status: Time Limit Exceeded

Solution code:
"""from collections import *
from itertools import *
from bisect import *
from heapq import *

import math
from fractions import gcd"""
import copy
N=int(input())
A=[list(reversed(list(map(int,input().split())))) for i in range(N)]
for i in range(N):
    for m in range(N-1):
        A[i][m]-=1

playerlst=set([i for i in range(N)])

count=0
while playerlst:
    lst=copy.copy(playerlst)
    flag=0
    while lst:
        p=lst.pop()
        p2=A[p][-1]
        if p2 in lst and A[p2][-1]==p:
            flag=1
            A[p].pop()
            A[p2].pop()
            lst.remove(p2)
            if not A[p]:
                playerlst.remove(p)
            if not A[p2]:
                playerlst.remove(p2)
    if not flag:
        print(-1)
        exit()
    count+=1
print(count)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
import math
from fractions import gcd
N=int(input())
A=[list(map(int,input().split())) for i in range(N)]
for i in range(N):
    for m in range(N-1):
        A[i][m]-=1
A=[list(reversed(a)) for a in A]
playerlst=set([i for i in range(N)])

count=0
while playerlst:
    lst=copy.copy(playerlst)
    flag=0
    while lst:
        p=lst.pop()
        p2=A[p][-1]
        if p2 in lst and A[p2][-1]==p:
            flag=1
            A[p].pop()
            A[p2].pop()
            lst.remove(p2)
            for P in [p,p2]:
                if not A[P]:
                    playerlst.remove(P)
    if not flag:
        print(-1)
        exit()
    count+=1
print(count)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
import math
from fractions import gcd
N=int(input())
A=[list(reversed(list(map(int,input().split())))) for i in range(N)]
for i in range(N):
    for m in range(N-1):
        A[i][m]-=1

playerlst=set([i for i in range(N)])

count=0
while playerlst:
    lst=copy.copy(playerlst)
    flag=0
    while lst:
        p=lst.pop()
        p2=A[p][-1]
        if p2 in lst and A[p2][-1]==p:
            flag=1
            A[p].pop()
            A[p2].pop()
            lst.remove(p2)
            for P in [p,p2]:
                if not A[P]:
                    playerlst.remove(P)
    if not flag:
        print(-1)
        exit()
    count+=1
print(count)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
	N = INT()
	A = [LIST() for _ in range(N)]

	match_id = [[0]*N for _ in range(N)]

	def toid(i, j):  # 選手から試合IDに変換
		if i > j: i, j = j, i
		return match_id[i][j]

	cnt = 0
	for i in range(N):
		for j in range(N):
			if i < j:
				match_id[i][j] = cnt
				cnt += 1

	V = N*(N-1)//2
	gout = [[] for _ in range(V)]
	deg = [0]*(V)
	for i in range(N):
		for j in range(N-2):
			gout[toid(i, A[i][j]-1)].append(toid(i, A[i][j+1]-1))
			deg[toid(i, A[i][j+1]-1)] += 1
			
	topo = [v for v in range(V) if deg[v]==0]
	day = [0]*V
	deq = deque(topo)
	ans = 0
	while deq:
	    v = deq.popleft()
	    for t in gout[v]:
	        deg[t] -= 1
	        if deg[t]==0:
	            deq.append(t)
	            day[t] = day[v] + 1
	            ans = day[t]
	if any(deg):  # 閉路あり
		print(-1)
		exit()
	print(ans+1)
	

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
	N = INT()
	A = [LIST() for _ in range(N)]

	graph_out = defaultdict(list)
	graph_in = defaultdict(list)
	match_id = [[0]*N for _ in range(N)]

	def toid(i, j):  # 選手から試合IDに変換
		if i > j: i, j = j, i
		return match_id[i][j]

	cnt = 0
	for i in range(N):
		for j in range(N):
			if i < j:
				match_id[i][j] = cnt
				cnt += 1

	V = N*(N-1)//2
	gout = [[] for _ in range(V)]
	gin = [[] for _ in range(V)]
	deg = [0]*(N*(N-1)//2)
	for i in range(N):
		for j in range(N-2):
			gout[toid(i, A[i][j]-1)].append(toid(i, A[i][j+1]-1))
			deg[toid(i, A[i][j+1]-1)] += 1
			gin[toid(i, A[i][j+1]-1)].append(toid(i, A[i][j]-1))
	# トポロジカルソート
	ans = list(v for v in range(V) if deg[v]==0)
	deq = deque(ans)
	used = [0]*V
	while deq:
	    v = deq.popleft()
	    for t in gout[v]:
	        deg[t] -= 1
	        if deg[t]==0:
	            deq.append(t)
	            ans.append(t)
	if any(deg):
		print(-1)
		exit()

	cnt = defaultdict(int)  # cntが入り次数に達したら発火
	day = defaultdict(int)
	q = deque(ans)
	for i, j in combinations(range(N), 2):
		match = match_id[i][j]
		if deg[match] == 0:  # 入り次数0
			day[match] = 1

	ans = 0

	while q:
		n = q.popleft()
		for node in gout[n]:
			cnt[node] += 1
			if cnt[node] == len(gin[node]):
				q.append(node)
				day[node] = day[n] + 1
				ans = day[node]
	print(ans) 

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
	N = INT()
	A = [LIST() for _ in range(N)]

	graph_out = defaultdict(list)
	graph_in = defaultdict(list)
	match_id = [[0]*N for _ in range(N)]

	def toid(i, j):  # 選手から試合IDに変換
		if i > j: i, j = j, i
		return match_id[i][j]

	cnt = 0
	for i in range(N):
		for j in range(N):
			if i < j:
				match_id[i][j] = cnt
				cnt += 1

	V = N*(N-1)//2
	g = [[] for i in range(V)]
	deg = [0]*(N*(N-1)//2)
	for i in range(N):
		for j in range(N-2):
			g[toid(i, A[i][j]-1)].append(toid(i, A[i][j+1]-1))
			deg[toid(i, A[i][j+1]-1)] += 1
			graph_in[toid(i, A[i][j+1]-1)].append(toid(i, A[i][j]-1))
			graph_out[toid(i, A[i][j]-1)].append(toid(i, A[i][j+1]-1))
	# トポロジカルソート
	ans = list(v for v in range(V) if deg[v]==0)
	deq = deque(ans)
	used = [0]*V
	while deq:
	    v = deq.popleft()
	    for t in g[v]:
	        deg[t] -= 1
	        if deg[t]==0:
	            deq.append(t)
	            ans.append(t)
	if any(deg):
		print(-1)
		exit()

	cnt = defaultdict(int)  # cntが入り次数に達したら発火
	day = defaultdict(int)
	q = deque([])
	for i, j in combinations(range(N), 2):
		match = match_id[i][j]
		if not graph_in[match]:  # 入り次数0
			q.append(match)
			day[match] = 1
	if not q:
		print(-1)
		exit()

	ans = 0

	while q:
		n = q.popleft()
		for node in graph_out[n]:
			if day[node]:  # 閉路
				print(-1)
				exit()
			cnt[node] += 1
			if cnt[node] == len(graph_in[node]):
				q.append(node)
				day[node] = day[n] + 1
				ans = day[node]
	print(ans) 

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
from bisect import bisect_left
import sys,math,itertools,pprint,fractions,time
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

st = time.time()
n = inp()
a = []
for i in range(n):
    b = inpl()
    a.append(deque(b))
zan = n*(n-1)//2
res = 0
while True:
    res += 1
    now = zan
    s = set()
    for i in range(n):
        if i in s or a[i] == deque([]): continue
        end = True
        chk = a[i][0] - 1
        if not chk in s and a[chk][0] == i+1:
            zan -= 1
            if not zan: 
                print(res); quit()
            a[i].popleft(); a[chk].popleft()
            s.add(i); s.add(chk)
        # print(res,i,chk,a)
    if now == zan or time.time() - st > 1700:
        print(-1)
        quit()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
from bisect import bisect_left
import sys,math,itertools,pprint,fractions,time
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

st = time.time()
n = inp()
a = []
for i in range(n):
    b = inpl()
    a.append(deque(b))
zan = n*(n-1)//2
res = 0
while True:
    res += 1
    now = zan
    s = set()
    for i in range(n):
        if i in s or a[i] == deque([]): continue
        end = True
        chk = a[i][0] - 1
        if not chk in s and a[chk][0] == i+1:
            zan -= 1
            if not zan: 
                print(res); quit()
            a[i].popleft(); a[chk].popleft()
            s.add(i); s.add(chk)
        # print(res,i,chk,a)
    if now == zan or time.time() - st > 1.8:
        print(-1)
        quit()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
from bisect import bisect_left
import sys,math,itertools,pprint,fractions,time
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

st = time.time()
n = inp()
a = []
for i in range(n):
    b = inpl()
    a.append(deque(b))
zan = n*(n-1)//2
res = 0
while True:
    res += 1
    now = zan
    s = set()
    for i in range(n):
        if i in s or a[i] == deque([]): continue
        end = True
        chk = a[i][0] - 1
        if not chk in s and a[chk][0] == i+1:
            zan -= 1
            if not zan: 
                print(res); quit()
            a[i].popleft(); a[chk].popleft()
            s.add(i); s.add(chk)
        # print(res,i,chk,a)
    if now == zan or st - time.time() > 1.8:
        print(-1)
        quit()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
from bisect import bisect_left
import sys,math,itertools,pprint,fractions
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n = inp()
a = []
for i in range(n):
    b = inpl()
    a.append(deque(b))
zan = n*(n-1)//2
res = 0
while True:
    res += 1
    now = zan
    s = set()
    for i in range(n):
        if i in s or a[i] == deque([]): continue
        end = True
        chk = a[i][0] - 1
        if not chk in s and a[chk][0] == i+1:
            zan -= 1
            if not zan: 
                print(res); quit()
            a[i].popleft(); a[chk].popleft()
            s.add(i); s.add(chk)
        # print(res,i,chk,a)
    if now == zan:
        print(-1)
        quit()

Submission status: Time Limit Exceeded

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

def main():
  n = int(input())
  U = n**2
  G = [[] for _ in range(U)]
  parent = [0]*U
  for i in range(n):
    A = list(map(lambda x:int(x)-1, input().split()))
    for j in range(n-2):
      a = A[j]
      b = A[j+1]
      G[min(i, a)*n+max(i, a)].append(min(i, b)*n+max(i, b))
      parent[min(i, b)*n+max(i, b)] += 1

  que = deque([(i*n+j, 1) for i in range(n-1) for j in range(i+1, n) if not parent[i*n+j]])
  ans = 1
  cnt = 0
  while que:
    v, t = que.pop()
    ans = max(ans, t)
    cnt += 1
    for nv in G[v]:
      parent[nv] -= 1
      if not parent[nv]:
        que.appendleft((nv, t+1))
  if cnt == n*(n-1)//2:
    print(ans)
  else:
    print(-1)
    
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
arr=[0]+[list(map(int,input().split())) for _ in range(n)]
pos=[0]*(n+1)
ans=0
while 1:
  flag=False
  cnt=0
  check=[0]*(n+1)
  for i in range(1,n+1):
    if check[i]==1:
      continue
    if pos[i]==n-1:
      cnt+=1
      continue
    pair=arr[i][pos[i]]
    if check[pair]==1:
      continue
    if arr[pair][pos[pair]]==i:
      flag=True
      pos[i]+=1
      pos[pair]+=1
      check[i]=1
      check[pair]=1
  if cnt==n:
    print(ans)
    break
  if flag==False:
    print(-1)
    break
  ans+=1

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
arr=[0]+[list(map(int,input().split())) for _ in range(n)]
pos=[0]*(n+1)
ans=0
while 1:
  flag=False
  cnt=0
  check=set()
  for i in range(1,n+1):
    if i in check:
      continue
    if pos[i]==n-1:
      cnt+=1
      continue
    pair=arr[i][pos[i]]
    if pair in check:
      continue
    if arr[pair][pos[pair]]==i:
      flag=True
      pos[i]+=1
      pos[pair]+=1
      check.add(i)
      check.add(pair)
  if cnt==n:
    print(ans)
    break
  if flag==False:
    print(-1)
    break
  ans+=1

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7

n=int(input())
a=[list(map(int,input().split())) for i in range(n)]
ans=0
lst=[]
for i in range(n):
    lst.append(deque(a[i]))
    # print(lst[i])
while 1:
    cnt=[0]*n
    ans+=1
    for i in range(n):
        if lst[i]!=deque():
            if cnt[i]==0  and cnt[lst[i][0]-1]==0 and lst[lst[i][0]-1][0]-1==i:
                cnt[i]=1
                cnt[lst[i][0]-1]=1
                lst[lst[i][0]-1].popleft()
                lst[i].popleft()
    # print(ans)
    # print(lst)
    for i in range(n):
        if cnt[i]==1:
            break
    else:
        print(-1)
        quit()
    
    for i in range(n):
        if lst[i]:
            break
    else:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
g = [[-1, -1] for i in range(n*n)]
z = [0] * (n*n)

a = []
for _ in range(n):
    a.append([int(i) for i in input().split()])

for i in range(n):
    for j in range(n-2):
        p, q = (i, a[i][j]-1)
        r, s = (i, a[i][j+1]-1)
        r, s = (min(r, s), max(r ,s))
        if p < q:
            g[p*n+q][0] = r*n + s
        else:
            g[q*n+p][1] = r*n + s
        z[r*n+s] += 1

from collections import deque
qu = set([])
for i in range(n):
    p, q = (i, a[i][0]-1)
    p, q = (min(p, q), max(p ,q))
    if z[p*n+q] == 0:
        qu.add(p*n+q)

ans = 0
re = 0
qu = deque(qu)
while True:
    nqu = deque()
    while qu:
        s = qu.popleft()
        re += 1
        for t in g[s]:
            if t != -1:
                z[t] -= 1
                if z[t] == 0:
                    nqu.append(t)
    ans += 1    
    qu = nqu
    if not qu:
        break

if re == n*(n-1)//2:
    print(ans)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
a = []
for i in range(n):
    a1 = list(map(int,input().split()))
    a.append(a1)
l = [[[] for i in range(n)] for i in range(n)]
c = 0
day = 0
for i in range(n):
    ap = [i,a[i][0]-1]
    ap.sort()
    for j in range(1,n-1):
        p = [i,a[i][j]-1]
        p.sort()
        l[ap[0]][ap[1]].append(p)
        ap = p
rl = [[0 for i in range(n)] for i in range(n)]
d = deque()
for i in range(n):
    for j in range(n):
        if i < j:
            if len(l[i][j]) > 0:
                for k in l[i][j]:
                    rl[k[0]][k[1]] = 1
#print(rl)
for i in range(n):
    for j in range(n):
        if i < j:
            if rl[i][j] == 0:
                d.append([[i,j],0])
rl=[[0 for i in range(n)] for i in range(n)]
al = []
key = 0
#print(l)
if len(d) == 0:
    key = 1
while len(d):
    now,day = d.pop()
    day += 1
    if len(l[now[0]][now[1]]) == 0:
        al.append(day)
    else:
        for i in l[now[0]][now[1]]:
            d.append([i,day])
    if day > n*(n-1)//2:
        key = 1
        break
if key == 1:
    print(-1)
else:
    print(max(al))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
a = []
for i in range(n):
    a1 = list(map(int,input().split()))
    a.append(a1)
l = [[[] for i in range(n)] for i in range(n)]
c = 0
day = 0
for i in range(n):
    ap = [i,a[i][0]-1]
    ap.sort()
    for j in range(1,n-1):
        p = [i,a[i][j]-1]
        p.sort()
        l[ap[0]][ap[1]].append(p)
        ap = p
rl = [[0 for i in range(n)] for i in range(n)]
d = deque()
for i in range(n):
    for j in range(n):
        if i < j:
            if len(l[i][j]) > 0:
                for k in l[i][j]:
                    rl[k[0]][k[1]] = 1
#print(rl)
for i in range(n):
    for j in range(n):
        if i < j:
            if rl[i][j] == 0:
                d.append([[i,j],0])
rl=[[0 for i in range(n)] for i in range(n)]
al = []
key = 0
#print(l)
if len(d) == 0:
    key = 1
while len(d):
    now,day = d.pop()
    if rl[now[0]][now[1]] == 0:
        rl[now[0]][now[1]] = 1
    else:
        key = 1
        break
    day += 1
    if len(l[now[0]][now[1]]) == 0:
        al.append(day)
        rl = [[0 for i in range(n)] for i in range(n)]
    else:
        for i in l[now[0]][now[1]]:
            d.append([i,day])
if key == 1:
    print(-1)
else:
    print(max(al))

Submission status: Time Limit Exceeded

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

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

ans = 0
match = N*(N-1)//2
player = set(range(N))
seen = [False]*N

while True:
    update = False
    checked = seen[::]
    ans += 1

    for x in player:
        if checked[x] or not A[x]:
            continue
        y = A[x][-1] - 1
        if A[y][-1]-1 == x and not checked[y]:
            A[x].pop()
            A[y].pop()
            checked[x] = True
            checked[y] = True
            update = True
            match -= 1

    if match <= 0:
        break

    if not update:
        ans = -1
        break

print(ans)

Submission status: Time Limit Exceeded

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

match = [0]*N

day = 0
while True:
    update = False
    done = [False] * N

    for a in range(N):
        if not A[a] or done[a]:
            continue
        b = A[a][0] - 1
        if not done[b] and A[b][0] - 1 == a:
            update = True
            done[a] = True
            done[b] = True
            A[a].popleft()
            A[b].popleft()

    if not update:
        break
    day += 1

ans = day
for a in A:
    if a:
        ans = -1
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
data_set=[0 for i in range(n)]
for i in range(n):
    a=list(map(int,input().split()))
    a.append(-1)
    data_set[i]=a
index=[0 for i in range(n)]
ans=-1
flag=True
now=[data_set[i][index[i]] for i in range(n)]
finished=[False for i in range(n)]
while flag:
    visited=[False for i in range(n)]
    sub=False
    for i in range(n):
        #nowリストのうち日ありからi+1番目のものについての一致条件の確認
        K=now[i]
        if now[K-1]==i+1 and not(visited[i] or visited[K-1]) and not(finished[i] or finished[K-1]):
                    visited[i]=True
                    visited[K-1]=True
                    index[i]+=1
                    index[K-1]+=1
                    sub=True
                    if index[i]==n-1:
                        finished[i]=True             
                    now[i]=data_set[i][index[i]]
                    if index[K-1]==n-1:
                        finished[K-1]=True                   
                    now[K-1]=data_set[K-1][index[K-1]]
    if not sub:
        flag=False
    ans+=1
judge=True
for i in range(n):
  if finished[i]==False:
    judge=False
    break
if judge:
  print(ans)
else:
  print(-1)