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 sys
from collections import deque
input = sys.stdin.readline

n = int(input())
a = []
for i in range(n):
    a_ = list(map(int, input().split()))
    tmp = []
    for i in range(len(a_)):
        tmp.append([a_[i],i+1])
    a.append(deque(tmp))

l = []
for i in range(n):
    l.append([i, 1])
q = deque(l)
count = 0
d = 0
while len(q) > 0:
    tmp = q.popleft()
    j = tmp[0]
    if len(a[j]) == 0:
        continue
    num = a[j][0][0] - 1
    if a[num][0][0] - 1 == j:
        d = max(a[j][0][1], a[num][0][1]) + 1
        q.append([num, d])
        q.append([j, d])
        _ = a[j].popleft()
        _ = a[num].popleft()
        count += 1
if count != n*(n-1)//2:
    print(-1)
    exit()
print(d)

Submission status: Wrong Answer

Solution code:
def main():

    n = int(input())
    listA=[] #appendのために宣言が必要
    for i in range(n):
        listA.append(list(map(int,input().split())))
    
    daied = 0
    days = 0
    error = 0

    for i in range(n):
        shiai = [0]*n
        if days < i-1:
            error = 1
            break
        else:
            for j in range(n-1):
                if 0 < len(listA[j]):
                    a = listA[j][0]
                    if 0 < len(listA[a-1]):
                        b = listA[a-1][0]-1
                        if( j == b and shiai[j] == 0 and shiai[a-1] == 0):
                            listA[j].pop(0)
                            listA[a-1].pop(0)
                            shiai[j] = 1
                            shiai[a-1] = 1
                            if days <= i:
                                days = i

    if error == 0:
        print(days+1)
    else:
        print(-1)

    

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

n = int(input())


def LIST():
    return list(map(int, input().split()))


A = []
for _ in range(n):
    A.append(LIST())

ans = 0
days = n * (n - 1) // 2

while 0 < days:
    meibo = [i for i, a in enumerate(A) if len(a) != 0]
    p = len(meibo)
    if p <= 0:
        break

    while 1 < p:
        i = meibo[0]
        x = A[i].pop(0)
        j = x - 1
        y = A[j].pop(0)

        if not j in meibo:
            meibo.remove(i)
            p -= 1
            continue

        if (i + 1) != y:
            print(-1)
            sys.exit()

        meibo.remove(i)
        meibo.remove(j)
        p -= 2

    ans += 1
    days -= 1
    p = n

meibo = [i for i, a in enumerate(A) if len(a) != 0]
print([-1, ans][len(meibo) == 0])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#ABC139 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
a = [deque() for _ in range(n)]
for i in range(1,n+1):
    x = LI()
    for j in x:
        a[i-1].append((i,j))
ans = 0
for j in range(n):
    f = defaultdict(lambda : 0)
    flg = False
    flg2 = False
    for i in range(n):
        if len(a[i]) == 0:
            continue
        (x,y) = a[i].popleft()
        flg2 = True
        if f[(x,y)] == 0 and f[(y,x)] == 1:
                flg = True
                f[(y,x)] = 0
        elif f[(x,y)] == 0:
            f[(x,y)] = 1
    if flg:
        ans += 1
    if not flg2:
        print(n)
        quit()
    for k,l in f.items():
        if l != 0:
            a[k[0]-1].appendleft(k)
for i in a:
    if len(i) != 0:
        print(-1)
        quit()
print(n)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list()
for i in range(N):
    A.append([int(a) - 1 for a in input().split()])
# print(A)

days = 0
for d in range(1, 2*N):
    # print('day:', d)
    game_counter = 0
    A_avail = [True for i in range(N)]
    for i in range(N):
        if len(A[i]) == 0:
            A_avail[i] = False
    if sum(A_avail) == 0:
        print(d - 1)
        break
    for i in range(N):
        # print('player:', i)
        if not A_avail[i]:
            # print('player is not available')
            continue
        e = A[i][0]
        # print(e, 'is enemy')
        if A_avail[e] and A[e][0] == i:
            # print(i, 'vs', e)
            A[i].pop(0)
            A[e].pop(0)
            A_avail[i] = False
            A_avail[e] = False
            game_counter += 1
        # print('')
    if game_counter == 0:
        print(-1)
        break

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#ABC139 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
a = [deque() for _ in range(n)]
for i in range(1,n+1):
    x = LI()
    for j in x:
        a[i-1].append((i,j))
ans = 0
for j in range(10*n):
    f = defaultdict(lambda : 0)
    flg = False
    flg2 = False
    for i in range(n):
        if len(a[i]) == 0:
            continue
        (x,y) = a[i].popleft()
        flg2 = True
        if f[(x,y)] == 0 and f[(y,x)] == 1:
                flg = True
                f[(y,x)] = 0
        elif f[(x,y)] == 0:
            f[(x,y)] = 1
    if flg:
        ans += 1
    if not flg2:
        print(ans)
        quit()
    for k,l in f.items():
        if l != 0:
            a[k[0]-1].appendleft(k)
for i in a:
    if len(i) != 0:
        print(-1)
        quit()
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

N = int(input())

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

print(-1)
sys.exit()

B = []
for i in range(N):
    tmp = [0] * N
    for j in range(N-1):
        tmp[A[i][j]-1] = j+1
    B.append(tmp)


ans = N-1
ans_tmp = 0
ans_tmp1 = 0
for i in range(N):
    ans_tmp = 0
    tmp = 0
    for j in A[i]:
        if B[j-1][i] > tmp:
            tmp = B[j-1][i]
        elif B[j-1][i] == tmp:
            ans_tmp += 1
        else:
            print(-1)
            sys.exit()
    ans_tmp1 = max(ans_tmp1, ans_tmp)

print(ans+ans_tmp1)

Submission status: Wrong Answer

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

n = int(input())
a = []
for i in range(n):
    a_ = list(map(int, input().split()))
    tmp = []
    for i in range(len(a_)):
        tmp.append([a_[i],i+1])
    a.append(deque(tmp))

l = []
for i in range(n):
    l.append([i, 1])
q = deque(l)
count = 0
while len(q) > 0:
    tmp = q.popleft()
    j = tmp[0]
    d = tmp[1]
    if len(a[j]) == 0:
        continue
    num = a[j][0][0] - 1
    if a[num][0][0] - 1 == j:
        q.append([num, max(a[num][0][1], a[j][0][1], d+1)])
        q.append([j, max(a[num][0][1], a[j][0][1], d+1)])
        _ = a[j].popleft()
        _ = a[num].popleft()
        count += 1
if count != n*(n-1)//2:
    print(-1)
    exit()
print(d)

Submission status: Wrong Answer

Solution code:
import sys
import math
from copy import deepcopy
from collections import deque, defaultdict
from operator import mul
from functools import reduce
sys.setrecursionlimit(20000000)

input = sys.stdin.readline


def main():
    N = int(input())
    players = []
    for i in range(N):
        pl = deque(map(int, input().split()))
        for x in range(len(pl)):
            pl[x] = pl[x] - 1
        players.append(pl)

    max_match = int(N * (N-1) / 2)
    match_count = 0
    days = 0

    for i in range(max_match):
        played = deque()
        no_match = True

        for p in range(len(players) - ((len(players) // 2) - 1)):
            main_p = p

            if main_p in played:
                continue

            if players[main_p]:
                opponent = players[main_p][0]

                if opponent in played or len(players[opponent]) == 0:
                    continue

                if main_p == players[opponent][0]:
                    no_match = False
                    played.append(players[main_p].popleft())
                    played.append(players[opponent].popleft())
                    match_count += 1

                    if match_count == max_match:
                        print(days + 1)
                        sys.exit()

        if no_match:
            print(-1)
            sys.exit()

        days += 1

    if days:
        print(days)
    else:
        print(-1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

date = 0
fin = set()
today = set()
while len(fin) != n:
    for i, vs in filter(lambda x: x[0] not in fin and x[0] not in today, enumerate(table, 1)):
        aite = vs[0]
        if aite not in today and table[aite - 1][0] == i:
            today.add(i)
            today.add(aite)
    if today:
        for i in today:
            table[i - 1].pop(0)
            if len(table[i - 1]) == 0:
                fin.add(i)
        date += 1
    else:
        print(-1)
        break
    today.clear()
print(date)

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = int(0)
A =[[0 for i in range(N)] for j in range(N)]
Lcandi = []
count =int(0)
Ln = int(0)
Lm = int(N*(N-1)//2)

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

while Ln<Lm:
    Lcandi = []
    Lnc = int(0)
    for i in range(N):
        if len(A[i]) != 0:
            if i+1 < A[i][0]:
                if not ([i+1,A[i][0]]) in Lcandi:
                    Lcandi.append([i+1, A[i][0]])
                else:
                    A[A[i][0]-1].remove(i+1)
                    A[i].remove(A[i][0])
                    Lnc +=1

            else:
                if not ([A[i][0],i+1]) in Lcandi:
                    Lcandi.append([A[i][0],i+1])
                else:
                    z=int(0)
                    z=A[i][0]
                    A[z-1].remove(i+1)
                    A[i].remove(A[i][0])
                    Lnc +=1

    print(Lcandi)
    if Lnc ==0:
        print("-1")
        exit()
    Ln += Lnc
    count +=1
    print(Ln)

print(count)

Submission status: Wrong Answer

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import bisect
from collections import deque

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

def LI(): return list(map(int, sys.stdin.readline().split()))

N = int(input())
B = [[] for i in range(N)]
for i in range(N):
    B[i] = LI()
    for j in range(N-1):
        B[i][j] -= 1

A = copy.deepcopy(B)
for i in range(N):
    A[i].reverse()

match = 1
ans = 1
answer_choice = []
while match:
    match = 0
    status = [i for i in range(N)]
    for now in status:
        if len(A[now]) == 0:
            pass
        else:
            enemy = A[now][0]
            if A[enemy][0] == now:
                answer_choice.append((enemy, now))
                A[enemy].pop(0)
                A[now].pop(0)
                match = 1
                try:
                    status.remove(enemy)
                except:
                    pass

if len(answer_choice) != (N-1)*N//2:
    print(-1)
    exit()

answer_choice.reverse()
tmp = []
for choice_i in answer_choice:
    i,j = choice_i
    if i in tmp or j in tmp:
        ans += 1
        tmp = [i,j]
        # continue
    else:
        tmp.append(i)
        tmp.append(j)

print(ans)

Submission status: Wrong Answer

Solution code:
# 2019/09/01

n=int(input())

g=[[0]*n for _ in range(n)]

a=[]
for i in range(n):
    a.append(tuple(map(lambda x: int(x)-1,input().split())))


i=0
for e in a:
    cnt=1
    for que in e:
        cnt=min(max(g[i][que],g[que][i]),cnt)
        g[i][que]=cnt
        g[que][i]=cnt
        cnt+=1
    i+=1

ans=0
for e in g:
    ss=set(e)
    if len(ss)!=len(e):
        print(-1)
        exit()
    ans=max(ans,max(e))

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
today = []
ans = 1
tomorrow = 0

while a:
    empty = 0
    for p in range(n):

        if not a[p]:
            empty += 1
            if empty == n-1:
                print(ans)
                sys.exit()
            continue

        if tomorrow == 0 and (p in today):
            if p == n-1:
                tomorrow = 1
            continue
        else:

            o = a[p][0] - 1

            if p == a[o][0] - 1:
                a[p].pop(0)
                a[o].pop(0)
                if (p in today) or (o in today):
                    ans += 1
                    today = [p, o]
                else:
                    today += [p, o]
                tomorrow = 0
                break
            else:
                if p == n-1:
                    print(-1)
                    sys.exit()

Submission status: Wrong Answer

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

day=0
game=0
num=[0]*n #index num
flag=1
while flag==1 and game<(n*(n-1)/2):
    flag=0
    iflg=0
    for i in range(n):
        iflg=0
        jflg=0
        for j in range(i+1,n):
            if num[i]<n-1 and num[j]<n-1 and iflg==0 and jflg==0:
                if a[i][num[i]]==j+1 and a[j][num[j]]==i+1:
                    #print(str(day)+"["+str(i)+","+str(j)+"]:"+str(a[i][num[i]])+" vs "+ str(a[j][num[j]]))
                    flag=1
                    iflg=1
                    jflg=1
                    game+=1
                    if game==int(n*(n-1)/2):
                        break
                    num[i]+=1
                    num[j]+=1
    day+=1
    
if flag==0:
    print("-1")
else:
    print(day)

Submission status: Wrong Answer

Solution code:
N = int(input())
days = 0  # 日数
tmp = []  # 対戦候補表（先頭ほど消化優先度高い）
done = []  # 1日の中ですでに対戦予定の入ったプレーヤ
T = [['' for _ in range(N - 1)] for __ in range(N)]  # 対戦表
flag = True  # 対戦が進行可能の場合、false
flag2 = True  # 対戦を1つ以上こなしてループした場合にはfalse
c = 0  # 対戦表追加初期値
for n in range(N):
    T[n] = input().split()
while c < N - 1:
    if flag2:
        for r in range(N):  # 直近対戦表追加
            if r + 1 < int(T[r][c]):
                tmp.append(str(r + 1) + T[r][c])
            else:
                tmp.append(T[r][c] + str(r + 1))
                c += 1
                flag = True
        flag2 = True
    for t in tmp:  # 対戦表の中でこなせる試合を探して消化
        if tmp.count(t) == 2 and not (t[0] in done or t[1] in done):
            flag = False
            flag2 = False
            done.append(t.split())
            tmp = [_ for _ in tmp if _ != t]
    if flag:
        print('-1')
        exit()
    days += 1
    done = []
print(str(days))

Submission status: Wrong Answer

Solution code:
import sys
n=int(input())
a=[list(map(int,input().split())) for i in range(n)]
day=0
while len(a)!=0:
  for i in range(n):
    for j in range(n):
      if a[i][0]==j+1!='*' and a[j][0]==i+1!='*':
        'a[i][0]'.replace('a[i][0]','*')
        'a[j][0]'.replace('a[j][0]','*')
  if '*' in a:
    print(a)
    a.remove('*')
    day+=1
  else:
    print(-1)
    sys.exit()
print(day)

Submission status: Wrong Answer

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

if N >= 900:
  X = N-10
else:
  X = N

while A != [[0]] * N:
  #print([[0]] * N)
  finish = [0] * N
  for i in range(X):
    #print(A, i)
    if A[i][0] > i:
      if (A[A[i][0] - 1][0] == i + 1) and (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
  #print(Q, A)
  #print(finish)
  if finish == H: #もし終わらないのに試合ができないなら-1で終了させる
    print("-1")
    quit()
  
print(day)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#ABC139 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
a = [deque() for _ in range(n)]
for i in range(1,n+1):
    x = LI()
    for j in x:
        a[i-1].append((i,j))
ans = 0
for j in range(5*n):
    f = defaultdict(lambda : 0)
    flg = False
    for i in range(n):
        if len(a[i]) == 0:
            continue
        (x,y) = a[i].popleft()
        if f[(x,y)] == 0 and f[(y,x)] == 1:
                flg = True
                f[(y,x)] = 0
        elif f[(x,y)] == 0:
            f[(x,y)] = 1
    if flg:
        ans += 1
    for k,l in f.items():
        if l != 0:
            a[k[0]-1].appendleft(k)
for i in a:
    if len(i) != 0:
        print(-1)
        quit()
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import collections

def solve(N: int, A: "List[List[int]]"):
    res = 0

    while any([len(a) > 0 for a in A]):
        matched = set()
        any_mached = False
        for i,a in enumerate(A): 
            if len(a) > 0 and i not in matched:
                enemy = a[0] - 1
                if len(A[enemy]) > 0 and enemy not in matched:
                    enemy_enemy = A[enemy][0] - 1
                    if i == enemy_enemy:
                        del A[i][0]
                        del A[enemy][0]
                        matched.add(i)
                        matched.add(enemy)
                        any_mached = True
        if not any_mached:
            res = -1
            break
        res += 1

    print(res)
    return

def solve2(N: int, A: "List[List[int]]"):
    res = 0

    A = { i : collections.deque([aa - 1 for aa in a]) for i,a in enumerate(A) }

    top_dic = collections.defaultdict(int)
    for k,v in A.items():
        top_dic[v[0]] += 1

    while len(A.items()):
        matched = set()
        del_keys = set()
        del_keys_top = set()
        any_mached = False
        
        keys = list(top_dic.keys())
        for i in keys: 
            if i not in matched:
                enemy = A[i][0]
                if enemy in A and enemy not in matched:
                    enemy_enemy = A[enemy][0]
                    if i == enemy_enemy:
                        top_i = A[i].popleft()
                        if not len(A[i]):
                            del_keys.add(i)
                        else:
                            top_dic[A[i][0]] += 1

                        top_dic[top_i] -= 1
                        if top_dic[top_i] <= 0:
                            del_keys_top.add(top_i)

                        top_e = A[enemy].popleft()
                        if not len(A[enemy]):
                            del_keys.add(enemy)
                        else:
                            top_dic[A[enemy][0]] += 1

                        top_dic[top_e] -= 1
                        if top_dic[top_e] <= 0:
                            del_keys_top.add(top_e)

                        matched.add(i)
                        matched.add(enemy)
                        any_mached = True
        if not any_mached:
            res = -1
            break

        for k in del_keys:
            del A[k]
        for k in del_keys_top:
            del top_dic[k]

        res += 1

    print(res)
    return

def solve3(N: int, A: "List[List[int]]"):
    res = 0

    A = { i : a for i,a in enumerate(A) }

    while len(A.items()):
        matched = set()
        del_keys = set()
        any_mached = False
        for i,a in A.items(): 
            if i not in matched:
                enemy = a[-1] - 1
                if enemy in A and enemy not in matched:
                    enemy_enemy = A[enemy][-1] - 1
                    if i == enemy_enemy:
                        A[i].pop()
                        if not len(A[i]):
                            del_keys.add(i)
                        A[enemy].pop()
                        if not len(A[enemy]):
                            del_keys.add(enemy)
                        matched.add(i)
                        matched.add(enemy)
                        any_mached = True
        if not any_mached:
            res = -1
            break

        for k in del_keys:
            del A[k]

        res += 1

    print(res)
    return

def solve4(N: int, A: "List[List[int]]"):
    res = 0

    A = { i : a for i,a in enumerate(A) }

    while len(A.items()):
        matched = set()
        del_keys = set()
        any_mached = False
        for i,a in A.items(): 
            if i not in matched:
                enemy = a[-1] - 1
                if enemy in A and enemy not in matched:
                    enemy_enemy = A[enemy][-1] - 1
                    if i == enemy_enemy:
                        A[i].pop()
                        if not len(A[i]):
                            del_keys.add(i)
                        A[enemy].pop()
                        if not len(A[enemy]):
                            del_keys.add(enemy)
                        matched.add(i)
                        matched.add(enemy)
                        any_mached = True
        if not any_mached:
            res = -1
            break

        for k in del_keys:
            del A[k]

        res += 1

    print(res)
    return

# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [ [ int(next(tokens)) for _ in range(N-1) ] for _ in range(N) ]  # type: "List[List[int]]"
    solve2(N, A)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

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

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

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

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

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

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

	ind = [0] * N
	ans = 0

	anfl = True

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

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

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

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

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

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

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

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

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



if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
from collections import deque
N=int(input())
M=(N*(N-1))//2
D=dict()
tmp=0
X=[(0,0) for i in range(M)]
G=[[] for i in range(M)]
for i in range(1,N+1):
    for j in range(1,N+1):
        if i<j:
            D[(i,j)]=tmp
            X[tmp]=(i,j)
            tmp+=1
A=[[int(j) for j in input().split()] for i in range(N)]
for i in range(N):
    for j in range(N-2):
        p1=D[(i+1,A[i][j])] if i+1<A[i][j] else D[(A[i][j],i+1)]
        p2=D[(i+1,A[i][j+1])] if i+1<A[i][j+1] else D[(A[i][j+1],i+1)]
        G[p1].append(p2)
K=[0 for i in range(M)]
for i in range(M):
    for p in G[i]:
        K[p]+=1
q=deque(i for i in range(M) if K[i]==0)
res=[]
while q:
    v1=q.popleft()
    res.append(v1)
    for v2 in G[v1]:
        K[v2]-=1
        if K[v2]==0:
            q.append(v2)
#print(D)
#print(res)
if len(res)<M:
    print(-1)
    exit()
def isok(x,y):
    a,b=X[x]
    c,d=X[y]
    if len({a,b,c,d})==4:
        return True
    else:
        return False
invres=[0 for i in range(M)]
for i in range(M):
    invres[res[i]]=i
#print(invres)
Y=[0 for i in range(M)]
for i in res:
    for j in G[i]:
        Y[invres[j]]=max(Y[invres[j]],invres[i]+1)
#print(Y)
dp=[0 for i in range(M)]
dp[0]=1
for i in range(1,M):
    flag=0
    for j in range(Y[i],i):
        if isok(res[i],res[j]):
            flag=1
            break
    if flag==0:
        dp[i]=dp[i-1]+1
    else:
        dp[i]=dp[i-1]
print(dp[-1])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys
input = sys.stdin.readline

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

progress_list = [0] * N
mans = [x for x in range(N)]
next_list = [a[0] - 1 for a in A]
day_limit = N * (N - 1) // 2 + 1
for i in range(day_limit):
    exhausted = [0] * N
    roop = True

    for man_idx in mans:
        opponent_idx = next_list[man_idx]
        if (opponent_idx <= -1) or exhausted[opponent_idx] or exhausted[man_idx]:
            continue

        opponents_opponent = next_list[opponent_idx]
        if man_idx == opponents_opponent:
            # print('day', i + 1, ',', man_idx + 1, opponent_idx + 1)
            exhausted[man_idx] += 1
            progress_list[man_idx] += 1
            if progress_list[man_idx] >= N - 1:
                mans.remove(man_idx)
               #  print(mans)

            # print(man_idx, progress_list[man_idx])
            next_list[man_idx] = A[man_idx][progress_list[man_idx]] - 1

            exhausted[opponent_idx] += 1
            progress_list[opponent_idx] += 1
            if progress_list[opponent_idx] >= N - 1:
                mans.remove(opponent_idx)
            next_list[opponent_idx] = A[opponent_idx][progress_list[opponent_idx]] - 1

            roop = False

    if roop:
        print(-1)
        exit()

    if not mans:
        print(i + 1)
        exit()

print(-1)

Submission status: Wrong Answer

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

n = int(input())

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

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