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:
import os
import sys
from collections import defaultdict
from functools import lru_cache

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

import time

st = time.time()

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

# グラフつくる
nodes = set()
graph = defaultdict(list)
ins = defaultdict(int)
sources = []
for i in range(N):
    for j in range(N - 2):
        a, b = i, A[i][j] - 1
        a, b = min(a, b), max(a, b)
        c, d = i, A[i][j + 1] - 1
        c, d = min(c, d), max(c, d)

        graph[a * N + b].append(c * N + d)
        ins[c * N + d] += 1
        sources.append(a * N + b)

        nodes.add(a * N + b)
        nodes.add(c * N + d)

# トポロジカルソート
S = []
for v in nodes:
    if ins[v] == 0:
        S.append(v)
L = []
while S:
    if time.time() - st >= 1.7:
        print(-1)
        exit()

    v = S.pop()
    L.append(v)
    for u in graph[v]:
        ins[u] -= 1
        if ins[u] == 0:
            S.append(u)

if len(L) != len(nodes):
    print(-1)
    exit()

seen = []


@lru_cache(maxsize=None)
def dfs(v):
    if time.time() - st >= 1.7:
        print(-1)
        exit()

    ret = 0
    for u in graph[v]:
        ret = max(ret, dfs(u))
    return ret + 1


ans = 0
for v in sources:
    ans = max(ans, dfs(v))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
MAX_INT = int(10e9)
MIN_NUM = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N = I()
a = [IL()[::-1] for i in range(N)]

cnt = N*(N-1)//2
flag = 1
days = 0
while flag:
  flag = 0
  used = [False]*N
  for i in range(N):
    #print(i+1)
    if len(a[i]) > 0 and used[i] == False:
      numIND = a[i][-1] -1
      #print(numIND)
      if a[numIND][-1] == i+1 and used[numIND] == False:
        a[i].pop(-1)
        a[numIND].pop(-1)
        used[i] == True
        used[numIND] = True
        flag = 1
        cnt -= 1
  else:
    days += 1
#print(a)
#print(cnt)
if cnt != 0:
  print(-1)
else:
  print(days)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
def input(): return sys.stdin.readline().strip()

def calc_matrix():
    i  = lambda: int(input())
    li = lambda: list(map(int, input().split()))
    
    N = i()
    M = [{} for _ in range(N)]
    M_v = [{} for _ in range(N)]
    
    for i in range(N):
        day = 1
        A = li()
        for a in A:
            if (a-1) in M_v[i].keys():
                if day > M_v[i][a-1]:
                    return '-1'
                day = M_v[i][a-1]
                continue
            while day in M[i].keys() or day in M[a-1].keys():
                day += 1
            M[i][day] = a-1
            M[a-1][day] = i
            M_v[i][a-1] = day
            M_v[a-1][i] = day
    return max([max(m.keys()) for m in M])

print(calc_matrix())

Submission status: Wrong Answer

Solution code:
import numpy as np

# A,B = list(map(int, input().split()))
N = int(input())

A_mat = np.zeros((N, N-1), dtype = np.int)
# print(A_mat)

for i in range(N):
    A_mat[i] = list(map(int, input().split()))
    # print(A_mat)
A_mat -= 1
# print(A_mat)
total_games = N * (N-1) // 2

days = 1

current_As = A_mat[:,0]
current_As_index = np.zeros((N),dtype = np.int)

already_played = []

# print(current_As)
games = 0
while True:
    todays_game = 0
    for i in range(N):
        opponent_index = current_As[i]
        if i in already_played or opponent_index in already_played:
            continue
        # print("i : {}, opponent_index : {}".format(i, opponent_index))
        if current_As[opponent_index] == i:
            current_As_index[i]+=1
            if current_As_index[i] < N-1:
                current_As[i] = A_mat[i, current_As_index[i]]

            current_As_index[opponent_index]+=1
            if current_As_index[opponent_index] < N-1:
                current_As[opponent_index] = A_mat[opponent_index, current_As_index[opponent_index]]

            games += 1
            todays_game += 1
            if games == total_games:
                print(days)
                exit()
            already_played += [i, opponent_index]
    if todays_game == 0:
        print("-1")
        exit()
    days += 1
    already_played = []
    # print()
    # print(current_As)
    # print(games)
    # print(days)
    # input("...")

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict


def dfs(root, links):
    status = {}
    ans = 0
    q = [(r, 0, 1) for r in root]
    while q:
        node = q.pop()
        if node[1] == 0:
            v, _, d = node
            ans = max(ans, d)
            q.append((v, 1))
            status[v] = 1
            d += 1
            for u in links[v]:
                if u in status:
                    if status[u] == 1:
                        return False
                else:
                    q.append((u, 0, d))
        else:
            status[node[0]] = 2
    return ans


n = int(input())
links = defaultdict(set)
may_root = set()
in_cnt = defaultdict(lambda: 0)
for i, line in enumerate(sys.stdin):
    aaa = list(map(int, line.split()))
    j = aaa[0] - 1
    a, b = (i, j) if i < j else (j, i)
    prev = a * 1000 + b
    may_root.add(prev)

    for j in aaa[1:]:
        j -= 1
        a, b = (i, j) if i < j else (j, i)
        key = a * 1000 + b
        links[prev].add(key)
        in_cnt[key] += 1
        prev = key
may_root = {r for r in may_root if in_cnt[r] == 0}

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

ans = dfs(may_root, links)
if ans == False:
    print(-1)
    exit()

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from sys import stdin

def main():
    N = int(input())
    A = [deque(map(int, input().split())) for _ in [0] * N]

    ans = 0
    while 1:
        flag = 0
        for i in range(N):
            j = A[i][0] - 1
            if j > i and A[j][0] - 1 == i:
                A[i][0] = A[j][0] = 0
                A[i].rotate(-1)
                A[j].rotate(-1)
                flag = 1
        if not flag:
            break
        ans += 1

    if not ans:
        print(-1)
    else:
        print(ans + 1)

input = lambda: stdin.readline()[:-1]
main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
N = int(input())
a_dict = defaultdict(list)
for i in range(N):
  a_dict[i] = [int(a) -1 for a in input().split()]

ans = 0
while len(a_dict) > 0:
  flag = False
  entried = []
  for i  in range(N):
    if len(a_dict[i]) > 0:
      i2 = a_dict[i][0]
      if a_dict[i2][0] == i and i not in entried and i2 not in entried:
        entried.extend([i,i2])
        del a_dict[i2][0], a_dict[i][0]
        if len(a_dict[i]) == 0: del a_dict[i]
        if len(a_dict[i2]) == 0: del a_dict[i2]
        flag = True
  if flag is False:break
  ans += 1
print(ans if ans != 0 else -1)

Submission status: Wrong Answer

Solution code:
from collections import deque
n=int(input())
A=[]
for i in range(n):
  A.append([int(i) for i in input().split()])
nn=n*(n-1)//2
F=[[0]*(n+1) for _ in range(n+1)]
cur=0
for i in range(1,n):
  for j in range(i+1,n+1):
    F[i][j]=cur
    F[j][i]=cur
    cur+=1
Edge=[[] for _ in range(nn)]
for i in range(n):
  s=F[i+1][A[i][0]]
  for j in range(1,n-1):
    t=F[i+1][A[i][j]]
    Edge[s].append(t)
    s=t
D=[0]*nn
Chk=[[False]*nn for _ in range(nn)]
loop=False
DD=deque()
for i in range(n):
  s=F[i+1][A[i][0]]
  if D[s]==0:
    DD.append(s)
    D[s]=1
while DD:
  s=DD.popleft()
  for g in Edge[s]:
    if D[s]+1>D[g]:
      if Chk[s][g]==True:
        loop=True
        break
      else:
        DD.append(g)
        D[g]=D[s]+1
        Chk[s][g]=True
print(-1 if loop==True else max(D))

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [list(map(int,input().split())) for _ in range(N)]
used = [0] * N
count = 0
while (min(used) != N-1 or max(used) !=N-1):

    temp = [-2] * N
    for i in range(N):
        now = used[i] 
        if used[i] == N-1:
            continue
        else:
            if temp[i] == -2:
                if temp[A[i][now]-1] == -2:
                    temp[A[i][now]-1] = i
                    used[i] += 1
                    temp[i] = -1
                else:
                    continue
            elif temp[i] != -1:
                if A[i][now]-1 == temp[i]:
                    used[i] += 1
                    temp[i] = -1
                else:
                    print(-1)
                    count = -100
                    break
            else:
                continue
    count += 1
    if count < 0:
        break
if count > 0:
    print(count)

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    tournament = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N)]
    map_que_tournament = {i:[] for i in range(N)} # player iがjと戦いたがってる
    competition_num = -1
    que_player = list(range(N))
    
    
    while que_player:
        day_process_flag = False
        new_queue = []
        # print(que_player)
        for player in que_player:
            if tournament[player]: 
                match_player = tournament[player].pop(0)
                # ぶじマッチング相手が見つかったら
                if map_que_tournament[match_player] and player == map_que_tournament[match_player][0]:
                    # print(player, match_player)
                    day_process_flag = True
                    new_queue.append(match_player)
                    new_queue.append(player)
                    map_que_tournament[match_player].pop()
                else:
                    map_que_tournament[player].append(match_player)
                    
        if day_process_flag:
            if competition_num < 0:
                competition_num = 1
            else: competition_num += 1
                
        que_player = new_queue
                
    print(competition_num)
    
solve()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
ans = 0
flag = True
for i in range(n - 1):
    for j in range(n):
        c = a[j][0]
        if c == "-":
            continue
        if j + 1 == a[c-1][0]:
            a[j][0] = "-"
            a[c-1][0] = "-"
    for j in range(n):
        if a[j][0] == "-":
            a[j] = a[j][1:]
            flag = False
    if flag:
        print(-1)
        break
if not flag:
    print(n)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = {i+1: list(map(int, input().split())) for i in range(n)}

ans = 1
while all(val != [] for val in a.values()):
    cache = []
    for i in range(1, n+1):
        if i in cache or a[i][0] in cache:
            continue
        if a[i] == []:
            continue
        if i == a[a[i][0]][0]:
            r = a[i].pop(0)
            cache.append(r)
            cache.append(a[r].pop(0))
    if cache == []:
        ans = -1
        break
    else:
        cache = []
    ans += 1

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import* #defaultdict Counter deque appendleft
import sys
input=sys.stdin.readline

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

    c=0
    while any(d.values()):
        c+=1
        skip=set()
        for i in range(1,n+1):
            if i not in skip.copy():
                if d[i]:
                    if d[i][0] in skip:
                        continue
                    else:
                        oppo=d[i].popleft()
                        if i!=d[oppo].popleft():
                            print(-1)
                            exit()
                        else:
                            skip.add(oppo)
                            skip.add(i)
#            print(c,i,d)
    print(c)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np

def main():
    N = int(input())
    arr = []
    for i in range(N):
        match = [int(num) for num in input().split()]
        arr.append([i + 1] + match)

    tarr = [list(x) for x in list(zip(*arr))]
    """
    nparr = np.array(arr)
    if (np.linalg.det(nparr) == 0):
        print(-1)
    else:
        print(N)
    """
    if (tarr == arr):
        print(-1)
    else:
        print(N)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import copy
n=int(input())
a=[[int(i)-1 for i in input().split()] for _ in range(n)]
day_check=[False for _ in range(n)]
day_cnt=0
match_cnt=0
while match_cnt<n*(n-1)//2:
    day_cnt+=1
    today_check=copy.copy(day_check)
    for i in range(n):
        if not a[i]:
            continue
        if today_check[i]:
            continue
        m=a[i][0]
        if a[m][0]==i and not today_check[m]:
            match_cnt+=1
            today_check[i]=True
            today_check[m]=True
            a[i].pop(0)
            a[m].pop(0)
        if not any(today_check):
            print(-1)
            exit()
print(day_cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [list(map(int,input().split())) for _ in range(N)]
last = N*(N-1)//2
answer = 0
nexts = set([])
avail = True
while avail:
    avail = False
    for i in range(N):
        if A[i]:
            if i+1 < A[i][0]:
                a = i+1
                b = A[i][0]
            else:
                b = i+1
                a = A[i][0]
            key = str(a)+str(b)
            if key in nexts:
                last -= 1
                avail = True
                A[A[i][0]-1].pop(0)
                A[i].pop(0)
            else:
                nexts.add(key)

    nexts = set([])
    answer += 1

if last==0:
    print(answer-1)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:

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

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

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

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
nt = []
for i in range(n):
  tmp = input().split()
  for j in range(n-1):
    tmp[j] = int(tmp[j])
  nt.append(tmp)

day = 0
j = []
for i in range(n):
  j.append(0)
  
while(True):
  print(j)
  tmp = []
  for i in range(n):
    if j[i] < n-1 and nt[nt[i][j[i]]-1][j[nt[i][ j[i] ]-1]] == i+1:
      tmp.append(i)
  print(tmp)
  if len(tmp) == 0:
    break
  for i in tmp:
    j[i] += 1
  day += 1
  
error = 0
for i in range(n):
  if j[i] != n-1:
    day = -1

print(day)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import copy
N = int(input())
A = [list(map(int, input().split())) for i in range(N)]
#print(2 ** (1/2))
day = 0

i = 0
while A != [[0]] * N :
  #print([[0]] * N)
  Q = copy.deepcopy(A)
  finish = [0] * N
  for i in range(N):
    #print(A, i)
    if A[A[i][0] - 1][0] == i + 1: #対戦可能な場合対戦。
      if (finish[i] == 0) and (finish[A[i][0]-1] == 0):
        x = A[i][0]
        A[i].pop(0)
        A[x - 1].pop(0)
        finish[i] == 1
        finish[x-1] == 1
        if len(A[i]) == 0:
          A[i].append(0)
        if len(A[x-1]) == 0:
          A[x-1].append(0)
        #print(A)
  day += 1
  #for i in range(N):#whileのおわる条件
    #if A[i] == []:
      #A[i] = 0
  #print(Q, A)
  if Q == A: #もし終わらないのに試合ができないなら-1で終了させる
    print("-1")
    quit()
  
print(day + 1)

Submission status: Wrong Answer

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

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n=I()

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

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

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

      if m[i]!=0:
        continue

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

        if a<i:
          continue

        if m[a]!=0:
          continue

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

  return ans

# main()
print(main())

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
fin = [False] * N
sleep = [False] * N
An = [''] * N
deg = [0] * N
for n in range(N):
    An[n] = deque([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 and sleep[n]==False]:
        if matched[n]:
            continue
        op = An[n][deg[n]]
        if matched[op - 1]:
            continue
        if An[op - 1][deg[op - 1]] == n + 1:
            flag = True
            matched[n] = True
            matched[op - 1] = True
            deg[n] += 1
            deg[op - 1] += 1
            sleep[op - 1] = False
            if deg[n] == N - 1:
                fin[n] = True
            if deg[op - 1] == N - 1:
                fin[op - 1] = True
        else:
            sleep[n] = True
    if not flag:
        days = -1
        break
print(days)

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    a = [list(map(int, input().rstrip('\n').split())) for _ in range(n)]
    ls = [0] * n
    mt = [0] * n
    cnt = 0
    bbb = 0

    for i in range(n):
        if ls[i] != -1:
            mt[i] = a[i][ls[i]]

    f = [False] * n
    
    for w in range(10 ** 15):
        cnt += 1
        bb = False
        update = []
        for i in range(n):
            if not f[i]:
                f[i] = True
                if ls[i] != -1:
                    if i + 1 == mt[mt[i]-1]:
                        f[i] = True
                        f[mt[i]-1] = True
                        bb = True
                        if ls[i] + 1 < n - 1:
                            ls[i] += 1
                            update.append(i)
                            f[i] = False
                        else:
                            ls[i] = -1
                            bbb += 1

                        if ls[mt[i]-1] + 1 < n - 1:
                            ls[mt[i]-1] += 1
                            update.append(mt[i]-1)
                            f[mt[i]-1] = False
                        else:
                            ls[mt[i]-1] = -1
                            bbb += 1
        for i in update:
            if ls[i] != -1:
                mt[i] = a[i][ls[i]]

        if bbb == n:
            print(cnt)
            exit()
        if not bb:
            print(-1)
            exit()


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
from collections import* #defaultdict Counter deque appendleft

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

    c=0
    while any(len(i) for i in d.values()):
        c+=1
        skip=set()
        for i in range(1,n+1):
            if i not in skip.copy():
                if d[i]:
                    if d[i][0] in skip:
                        continue
                    else:
                        oppo=d[i].popleft()
                        if i!=d[oppo].popleft():
                            print(-1)
                            exit()
                        else:
                            skip.add(oppo)
                            skip.add(i)
#            print(c,i,d)
    print(c)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
n=int(input())
outs=[[] for i in range(1000000)]
ins=[0]*1000000
for i in range(n):
    a_list=list(map(int,input().split()))
    for j in range(1,n-1):
        x1=min(i,a_list[j-1]-1)
        y1=max(i,a_list[j-1]-1)
        z1=x1*1000+y1
        x2=min(i,a_list[j]-1)
        y2=max(i,a_list[j]-1)
        z2=x2*1000+y2
        outs[z1].append(z2)
        ins[z2]+=1
q=[]
for i in range(n):
    for j in range(i+1,n):
        if ins[1000*i+j]==0:
            q.append(1000*i+j)
res=[]
ans=1
s=set()
while q:
    v1=q.pop()
    x=v1//1000
    y=v1%1000
    if x in s or y in s:
        ans+=1
        s=set([x,y])
    else:
        s.add(x)
        s.add(y)
    res.append(v1)
    for v2 in outs[v1]:
        ins[v2]-=1
        if ins[v2]==0:
            q.append(v2)
if len(res)==n*(n-1)//2:
    print(ans)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
dic = {}
for i in range(N):
  dic[i+1] = deque([int(i) for i in input().split()])

ans = 0
while (True):
  tmpset = set()
  playcount = 0
  for i in range(1, N+1):
    if i not in tmpset and len(dic[i]) > 0:
      aite = dic[i][0]
      if aite not in tmpset and dic[aite][0] == i:
        dic[i].popleft()
        dic[aite].popleft()
        tmpset.add(i)
        tmpset.add(aite)
        playcount += 1
  if playcount > 0:
    ans += 1
  if playcount == 0:
    break
failedflag = False
if ans < N:
  failedflag=True
if failedflag:
  print(-1)
else:
  print(ans)

Submission status: Wrong Answer

Solution code:
#

def main():
    n = int(input())
    agrid = []
    agrid_pointer = [0] * n

    for i in range(n):
        al = list(map(int, input().split()))
        for j in range(len(al)):
            al[j] -= 1
        agrid.append(al)

    ans = 0
    while True:
        match = set()
        for i in range(n):
            if agrid_pointer[i] == n - 1 or i in match:  # もう全部対戦済み or この日対戦済み
                continue

            target = agrid[i][agrid_pointer[i]]
            if agrid_pointer[target] == n - 1 or target in match:  # もう全部対戦済み or この日対戦済み
                continue

            if agrid[target][agrid_pointer[target]] == i:
                # can match
                agrid_pointer[i] += 1
                agrid_pointer[target] += 1

                match.add(i)
                match.add(target)
            else:  # 次対戦できないからのその対戦相手とのマッチを試す
                target_target = agrid[target][agrid_pointer[target]]
                if agrid_pointer[target_target] == n - 1 or target_target in match:  # もう全部対戦済み or この日対戦済み
                    # can match
                    agrid_pointer[target_target] += 1
                    agrid_pointer[target] += 1

                    match.add(target_target)
                    match.add(target)

            if len(match) == n or len(match) == n - 1:  # 全員試合することが決まったら
                break

        # print(match)
        if len(match) == 0:  # 対戦がなくなったら
            break
        ans += 1

    # print(aconditions)
    # 対戦が残ってたら
    for p in agrid_pointer:
        if p != n - 1:
            print(-1)
            return
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
MAX_INT = int(10e9)
MIN_NUM = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N = I()
a = [IL()[::-1] for i in range(N)]

cnt = N*(N-1)//2
flag = 1
days = 0
while flag:
  flag = 0
  for i in range(N):
    used = [False]*N
    if len(a[i]) > 0 and used[i] == False:
      numIND = a[i][-1] -1
      if a[numIND][-1] == i+1 and used[numIND] == False:
        a[i].pop(-1)
        a[numIND].pop(-1)
        used[i] == True
        used[numIND] = True
        flag = 1
        cnt -= 1
  else:
    days += 1
#print(a)
#print(cnt)
if cnt != 0:
  print(-1)
else:
  print(days)

Submission status: Wrong Answer

Solution code:

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

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

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

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

Submission status: Wrong Answer

Solution code:
n = int(input())
a = []
for i in range(n):
  a_tmp = list(map(int, input().split(' ')))
  a.append(a_tmp)
#print(a)

shiai_lists = []
shiai = {}
for i in range(n):
  shiai_lists_tmp = []
  for j in range(n - 1):
    shiai_lists_tmp.append(tuple(sorted([i + 1, a[i][j]])))
    shiai[tuple(sorted([i + 1, a[i][j]]))] = 0
  shiai_lists.append(shiai_lists_tmp)
    
#print(shiai_lists)
#print(shiai)

for sl in shiai_lists:
  for i, sli in enumerate(sl):
    shiai[sli] += i
#print(shiai)
ans = len(set(shiai.values()))
check = min(shiai.values())
if check != 0:
  print(-1)
else:
  print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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