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: Wrong Answer

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


import queue

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



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

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

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

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

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

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

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







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


import queue

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



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

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

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

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

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

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

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







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


import queue




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

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

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

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

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

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

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







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


import queue




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

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

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

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

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

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

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







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


import queue




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

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

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


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

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

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

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







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


import queue




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

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

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


    q = queue.Queue()
    count_node = 0

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

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

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







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())

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

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

Submission status: Wrong Answer

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

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

    edge = defaultdict(list)

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

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

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

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

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

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




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

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

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

    print(day)"""

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


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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

    edge = defaultdict(list)

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

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

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

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

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

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




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

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

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

    print(day)"""

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


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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

from collections import deque
import queue




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

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

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


    q = deque()
    count_node, ans = 0, 0

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

    while len(q):
        now_node, length = q.pop()
        # if length < length_data[now_node]:
        #     continue

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

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







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())

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

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

Submission status: Wrong Answer

Solution code:
N = int(input())
indexes = [0] * (N+1)
matches = [[0] * (N-1)] + [list(map(int, input().split())) for _ in range(N)]
cnt = 0
while True:
  play = False
  check_cnt = 0
  for idx, match in enumerate(matches):
    if idx == 0:
      continue
    else:
      if indexes[idx] == N-1:
        check_cnt += 1
        continue
      opponent = match[indexes[idx]]
      if idx == matches[opponent][indexes[opponent]]:
        play = True
        indexes[idx] += 1
        indexes[opponent] += 1
  if play:
    cnt += 1
  else:
    if check_cnt == N:
      print(cnt+1)
      break
    else:
      print(-1)
      break

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import sys
n=int(input())
a=[]
for i in range(n):
  a.append(list(map(int,input().split())))
maxmatch=n*(n-1)
day=0

match=[0]*(n+1)
check=[0]*(n+1)
while True:
  day+=1
  for i in range(n):
    if match[i]>=n-1:
      check[i]=day
    if check[i]==day:
      continue
    else:
      vs=a[i][match[i]]-1
      if check[i] and check[vs] and a[vs][match[vs]]-1==i:
        match[i]+=1
        match[vs]+=1
        match[n]+=2
        check[i]=day
        check[vs]=day
        check[n]=day
      
    if i==n-1:
      if check[n]!=day:
        print(-1)
        sys.exit()
  if match[n]==maxmatch:
    break
        
print(day)

Submission status: Wrong Answer

Solution code:
#記録用

import sys
sys.exit()
def return_if_the_all_the_elements_are_n(lst):#全ての要素が"n"のときYesを返す
    for i in range(1,n):
        if lst[0]=="n" and lst[0]==lst[i]:pass
        else:return 0
    return 1
    
def return_soushisouai(A,n):#相思相愛の相手がいれば"o"を、すでに試合を終えている場合は"n"をリストに格納する
    desired_opponets=[]
    for i in range(n):
        if len(A[i])!=0:desired_opponets.append(A[i][0])
        else:desired_opponets.append("n")
        
    for i in range(len(desired_opponets)):
        for j in range(len(desired_opponets)-i):
            if desired_opponets[i]=="o":#すでに相手が決まっている場合、次の人の探索へ
                break
            
            if desired_opponets[i]==i+j+1 and desired_opponets[i+j]==i+1:#相思相愛の相手が見つかった場合
                desired_opponets[i]="o"
                desired_opponets[i+j]="o"
                break
            
            else:pass
        
    if "o" not in desired_opponets:
        if return_if_the_all_the_elements_are_n(desired_opponets):return"end"#全ての要素が"n"＝試合が終わった場合
        else:return "no match"
    else:return desired_opponets
    
n = int(input())
A=[]
for i in range(n):
    A.append(list(map(int,input().split())))
  
  
day=0
while(True):
    match = return_soushisouai(A,n)
    #print(A,match)
    if match=="no match":
        print(-1)
        sys.exit()
    elif match=="end":break
    else:
        day+=1
        for i in range(n):
            if match[i]=="o":del A[i][0]
print(day)

Submission status: Wrong Answer

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

n = int(input())
a = [deque([x for x in list(map(int, input().split()))]) for _ in range(n)]
nokori_games = n * (n - 1) / 2 
day = 1
for ii in range(3500):
  player_in_this_game = set()
 
  for m in range(n): #選手ごとに判定
    #整合性のある対戦組み合わせがあれば配列から消す
    #全員の判定が終わって試合が残っていたら1日増やす
    la = len(a[m])      
    if la: #選手に試合予定が残っている
      teki = a[m][0] #対戦相手
      jibun = m + 1 #自分
      if a[teki - 1][0] == jibun:
        if m in player_in_this_game or teki - 1 in player_in_this_game:
          #自分または相手に既に試合が組まれている
          pass
        else: #対戦相手の予定も自分でかつ相手がこのターンで試合中ではない
          a[m].popleft() #自分の予定を消す
          a[teki - 1].popleft() #相手の予定を消す
          player_in_this_game.add(m) #自分を試合中にする
          player_in_this_game.add(teki - 1) #相手を試合中にする
          nokori_games -= 1 #残り試合予定を1つ減らす

  if nokori_games: #残り試合があるのに
    if not len(player_in_this_game): #今回対戦が組まれなければ残りの予定が不整合なのでエラー
      print(-1)
      sys.exit()
  else: #誰も残り試合予定がなければ終了
    print(day)
    sys.exit()
  day += 1

Submission status: Wrong Answer

Solution code:
import sys

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

canUse = set(range(N))

ans = 0
done = 0
while done < N:
    ans += 1
    canUseNew = set()
    print("LC", len(canUse))
    for n in canUse:
        if not A[n]:
            continue

        first = A[n][-1]
        if first in canUseNew or n in canUseNew:
            continue

        if A[first][-1] == n:
            # print("Do", n + 1, first + 1)
            A[n].pop()
            if len(A[n]) == 0:
                done += 1
            A[first].pop()
            if len(A[first]) == 0:
                done += 1
            canUseNew.add(n)
            canUseNew.add(first)

    if len(canUseNew) == 0:
        print(-1)
        sys.exit(0)
    canUse = canUseNew

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

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

canUse = set(range(N))

ans = 1
while any([len(i) > 0 for i in A]):
    ans += 1
    canUseNew = set()
    for n in canUse:
        if not A[n]:
            continue

        first = A[n][0]
        if A[first][0] == n:
            # print("Do", n, first)
            A[n].pop(0)
            A[first].pop(0)
            canUseNew.add(n)
            canUseNew.add(first)

    if len(canUseNew) == 0:
        print(-1)
        sys.exit(0)
    canUse = canUseNew

print(ans)