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:

def main():
    import sys
    input = sys.stdin.readline
    N = int(input())

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

Submission status: Wrong Answer

Solution code:
n = int(input())

league = [ [ int(v)-1 for v in input().split() ] for i in range(n) ]
done = [ 0 for i in range(n) ]

def day():
    day = 1
    day_match = 0
    match = [ 0 for i in range(n) ]
    for _ in range(n-1):
        for i in range(n):
            j = league[i][done[i]]
            if i != j and league[j][done[j]] == i:
                league[i][done[i]] = i
                league[j][done[j]] = j

                if match[i] == 1 or match[j] == 1:
                    day += 1
                    match = [ 0 for i in range(n) ]
                match[i] = 1
                match[j] = 1
                day_match += 1
                if done[i] < n-2:
                    done[i] += 1
                if done[j] < n-2:
                    done[j] += 1

    return day_match, day

cal_match = (n*n-n) // 2
[total_match, days] = day()

if total_match == cal_match:
    print(days)
else:
    print(-1)

Submission status: Wrong Answer

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


def solve(N: int, A: "List[List[int]]"):
    flag = True
    counter = 0
    while flag:
        tmp = [a[0] for a in A]
        p_idx = []
        for i, t in enumerate(tmp):
            if i == tmp[t]:
                p_idx.append(i)
        if len(p_idx) == 0 or counter > 2 * N:
            print(-1)
            return
        for p in p_idx:
            A[p].pop(0)
            A[p].append(-1)
        if all([a[0] == -1 for a in A]):
            flag = False
        counter += 1
    print(counter)
    return


# Generated by 1.1.5 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)) - 1 for _ in range(N - 1)] for _ in range(N)]  # type: "List[List[int]]"
    solve(N, A)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())

# 各日付ごとの対戦を記録していく
schedule = []

  
# まず、選手１の条件を満たすように　N-1　日の日程を決める
# 次に、選手２の条件を満たすように日程を決める
# これを選手Nまで繰り返し、どこかで error が出るかを調べる

def set_matches(athlete, match_list, schedule):
  if schedule == []:    
    for match in match_list:
      schedule.append([athlete, match])
  else:
    tmp = 0
    for match in match_list:
      flag = True
      for i in range(tmp, len(schedule)):
        day = schedule[i]
                
        if athlete in day and match in day:
          flag = False
          tmp = i+1
          break
        elif athlete not in day and match not in day:
          day.append(athlete)
          day.append(match)
          flag = False
          tmp = i+1
          break
        elif (athlete in day) ^ (match in day):
          tmp = i+1
      if flag:   
      	schedule.append([athlete, match])      
      
  return schedule

for i in range(N):
  ai = tuple(map(int, input().split()))
  schedule = set_matches(i+1, ai, schedule)

if len(schedule) > (N * (N-1) // 2):
  print(-1)
else:
  print(len(schedule))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
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 LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7



def main(): 
    N = II()
    A = [[] for _ in range(N)]
    for i in range(N):
        A[i] = LI()

    # print(A)
    # return

    from collections import defaultdict
    outs = defaultdict(list)
    ins = defaultdict(int)
    for i in range(N):
        # prev_v = (i+1, A[i][0]) if i+1 < A[i][0] else (A[i][0], i+1)
        for j in range(1,N-1):
            prev_v = (i+1, A[i][j-1]) if i+1 < A[i][j-1] else (A[i][j-1], i+1)
            outs[prev_v].append((i+1, A[i][j]) if (i+1 < A[i][j]) else (A[i][j] , i+1))
            ins[(i+1, A[i][j]) if (i+1 < A[i][j]) else (A[i][j], i+1)] += 1

    # print(outs, ins)
    # return

    from collections import deque
    q = deque()
    for i in range(1,N+1):
        for j in range(1, N+1):
            if i != j and i < j and ins[(i, j)] == 0:
                q.append((i, j))

    # q = deque(v1 for v1 in range(1, N+1) if ins[v1] == 0)
    res = []
    while q:
        v1 = q.popleft()
        res.append(v1)
        for v2 in outs[v1]:
            ins[v2] -= 1
            if ins[v2] == 0:
                q.append(v2)

    # print(res)  # トポロジカルソート済
    # print(', '.join(res))
    if len(res) == 0:
        print(-1)
        return

    print(42)

main()

Submission status: Wrong Answer

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

t = N * (N-1) // 2
I = [0] * N
isEnd = [False] * N

end = 0
for d in range(t):
    if end == N:
        print(d)
        break
    played = [False] * N
    n = 0
    for p1 in range(N):
        if played[p1] or isEnd[p1]:
            continue
        p2 = A[p1][I[p1]] - 1
        if p2 < p1 or played[p2] or isEnd[p2]:
            continue
        if A[p2][I[p2]] - 1 == p1:
            print(p1, p2)
            I[p1] += 1
            I[p2] += 1
            played[p2] = True
            if I[p1] == N - 1:
                end += 1
                isEnd[p1] = True
            if I[p2] == N - 1:
                end += 1
                isEnd[p2] = True
            n += 1
    if n == 0:
        print(-1)
        break
else:
    print(t)

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=0
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+=1
    for v2 in outs[v1]:
        ins[v2]-=1
        if ins[v2]==0:
            q.append(v2)
if res==n*(n-1)//2:
    print(ans)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
def resolve():
    n = int(input())
    am = []

    from collections import deque

    for i in range(n):
        am.append(deque(list(map(lambda x: int(x) - 1, input().split()))))

    cnt = n * (n - 1) // 2

    res = 0
    while cnt > 0:
        day = 0
        match = 0
        done = {}
        for i in range(n):
            if i in done:
                continue
            if len(am[i]) == 0:
                continue
            j = am[i][0]
            if am[j][0] == i:
                to_do_day = 1
                if j in done:
                    to_do_day = done[j] + 1
                am[i].popleft()
                am[j].popleft()
                done[i] = to_do_day
                done[j] = to_do_day
                day = max(day, to_do_day)
                match += 1

        if match == 0:
            print(-1)
            return
        else:
            cnt -= match

        res += day

    print(int(res))
    
resolve()

Submission status: Wrong Answer

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

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

    if day > 1000:
        print(500*499)
        sys.exit()
    
    
print(day)

Submission status: Wrong Answer

Solution code:
N=int(input())

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

s=1
d=0
c=0
while s!=0:
    s=0
    d+=1
    o=list(range(N))
    ss=0
    for i in o:
        if A[A[i][0]-1][0]==i+1 and A[i][0]>i:
            s+=1
            c+=1
            o.pop(ss+A[i][0]-2-i)
            A[A[i][0]-1].pop(0)
            if A[A[i][0]-1]==[]:
                A[A[i][0]-1].append(-1)
            A[i].pop(0)
            if A[i]==[]:
                A[i].append(-1)


if c!=N*(N-1)/2:
    print(-1)
else:
    print(d-1)

Submission status: Wrong Answer

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


def solve(N: int, A: "List[List[int]]"):
    flag = True
    counter = 0
    while flag and counter < 2 * N:
        tmp = [a[0] for a in A]
        p_idx = []
        for i, t in enumerate(tmp):
            if i == tmp[t]:
                p_idx.append(i)
        if len(p_idx) == 0:
            print(-1)
            return
        for p in p_idx:
            A[p].pop(0)
            A[p].append(-1)
        if all([a[0] == -1 for a in A]):
            flag = False
        counter += 1
    print(counter)
    return


# Generated by 1.1.5 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)) - 1 for _ in range(N - 1)] for _ in range(N)]  # type: "List[List[int]]"
    solve(N, A)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys, math; from collections import deque; readline=sys.stdin.readline;

N = int(readline())
A = [deque(map((lambda x:int(x) - 1), readline().split())) for n in range(N)]


count = 0
while True:
    locked = [False for n in range(N)]
    pop_count = 0
    for n in range(N):
        if locked[n]:
            continue
        if len(A[n]) == 0:
            continue
        a = n
        locked[n] = True
        while True:
            b = A[a][0]
            if locked[b]:
                break
            if a == A[b][0]:
                A[a].popleft()
                A[b].popleft()
                locked[b] = True
                pop_count += 1
                break
            locked[b] = True
            a = b
        
    if pop_count == 0:
        break
    else:
        count += 1

if count == 0:
    print(-1)
else:
    print(count)

Submission status: Wrong Answer

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

ans = 0

prog = []
today = []
done = []
for i in range(n+1):
  prog.append(0)
  today.append(0)
  done.append(0)

while True:
  next = 0
  for i in range(n+1):
    today[i] = 0
  for i in range(1, n+1):
    # print(i, a[i])
    # print(a[i][prog[i]], a[a[i][prog[i]]])
    # print(a[i][prog[i]], a[a[i][prog[i]]][prog[a[i][prog[i]]]])

    if today[a[i][prog[i]]] == 0 and a[i][prog[i]] > i and a[a[i][prog[i]]][prog[a[i][prog[i]]]] == i:
      today[a[i][prog[i]]] = 1
      prog[a[i][prog[i]]] += 1
      # print(a[i][prog[i]], prog[a[i][prog[i]]])
      if prog[a[i][prog[i]]] == (n - 1):
        done[a[i][prog[i]]] = 1
      prog[i] += 1
      # print(i, prog[i])
      if prog[i] == (n - 1):
        done[i] = 1
      next = 1
  # print('prog', prog)
  # print('done', done)
  ans += 1
  if next == 0:
    for i in range(1, n+1):
      if done[i] != 1:
        print(-1)
        exit()
    print(ans-1)
    exit()

Submission status: Wrong Answer

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

n = int(input())

dict = {}
for x in range(1, n+1):
    dict[x] = list(map(int, input().split()))
#print(dict)

def battle():
    isOccup = [False for _ in range(n+1)]

    for x in range(1, n+1):

        #もしdict[x]が空いているならば
        if not dict[x]:
            continue
        else:
            #PLxを選択
            pickOpp = dict[x][0]

            #PLxがまだ空いているならば
            if isOccup[pickOpp] == False:
#                print("PL"+str(x)+" is picked: first opponent:"+str(pickOpp))


                #もし最初の対戦相手がxならば
                if dict[pickOpp][0] == x:
#                    print("PL"+str(pickOpp)+" vs PL"+str(x)+" reserved")
                    #isOccupフラグを変更
                    isOccup[x] = True
                    isOccup[pickOpp] = True
                    #消化済の対戦相手を削除
                    del dict[x][0]
                    del dict[pickOpp][0]
                else:
                    continue

#dictのすべての要素が空なら
def checkEmpty():
        dictIsEmpty = True
        for i in range(1, n+1):
            if len(dict[i]) != 0:
                dictIsEmpty = False
            else:
                continue
        if dictIsEmpty == True:
            return True
        else:
            return False


d = 0        
while(d < 10**6):
    d += 1
    try:
        if checkEmpty() == False:
            battle()
#           print(isOccup)
#           print(dict)
        else:
            break
    #IndexErrorが起きたらdictをチェックする
    except IndexError:
        pass
#        print("IndexError")

print(d)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = deque()
for i in range(N):
    Ai = deque(map(int, input().split()))
    A.append(Ai)

tmp = 0
cnt = 0
ans = 2
while cnt < N:

    if tmp > N-1:
        tmp = 0
        if cnt < N:
            cnt = 0
        else:
          break
        continue
    if len(A[tmp]) == 0:
        tmp += 1
        cnt += 1
        continue
    if tmp == A[A[tmp][0]-1][0]-1:
        A[A[tmp][0]-1].popleft()
        A[tmp].popleft()
        tmp += 1
    else:
        tmp += 1
        cnt += 1
    
    if tmp > N-1:
        tmp = 0
        if cnt >= N:
            break
        cnt = 0
        ans += 1

for i in range(N):
    if len(A[i]) != 0:
        print(-1)
        exit()
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

# A = [[0 for _ in range(N-1)] for __ in range(N)]
day = 1
A = [None for _ in range(N)]
for player in range(N):
    A[player] = [int(_)-1 for _ in input().split()]

player_complet_flags = [True for _ in range(N)]

while all(player_complet_flags) == True:
    # プレイヤーの試合数の限度:1 
    poosible = [True for _ in range(N)]
    # プレイヤーごとに
    for player in range(N):
        # 試合可能ならば
        if poosible[player] == True:
            # 最初の対戦相手を見る
            opponent = A[player][0]
            # 相手の最初の対戦相手がplayerで相手が対戦可能であれば
            if A[opponent][0] == player and poosible[opponent]==True:
                a, b = A[player].pop(0), A[opponent].pop(0)
                poosible[player] = False
                poosible[opponent] = False
    # 全ての試合が終わったplayerがいたら
    for player in range(N):
        if len(A[player]) == 0:
            player_complet_flags[player] = False

    day += 1
    # 可能で無い場合
    if all(poosible) == True:
        day = -1
    

print(day)

Submission status: Wrong Answer

Solution code:
#E問題
N = int(input())
A = [list(map(int,input().split())) for i in range(N)]
"""
for i in range(N):
    for j in range(N-1):
        A[i][j]-=1
"""
flag = 0
M = (N*(N+1))//2
for j in range(N-1):
    SUM = 0
    for i in range(N):
        SUM+=A[i][j]
    if SUM == M:
        flag = 1
    else:
        flag = 0
        
if flag == 1:
    print(-1)
else:
    print(N)

Submission status: Wrong Answer

Solution code:

def main():
    import sys
    input = sys.stdin.readline
    N = int(input())

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

Submission status: Wrong Answer

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

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

b = [[0] * n for i in range(n)]

for i in range(n):
    for j in range(n-1):
        b[i][a[i][j]] = max(j+1, b[i][a[i][j]])
        b[a[i][j]][i] = max(j+1, b[a[i][j]][i])


ans = 0
for i in range(n):
    # print(b[i])
    c = b[i]
    c.sort()
    x = 0
    for j in range(1, n):
        if c[j] == c[j-1]:
            x += 1
    cand = c[-1] + x
    ans = max(ans, cand)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
n = int(input())
alist = []
for i in range(n):
    alist.append(list(map(int, input().split())))

point = 0
kazu = 0
while True:
    y = []
    for i in range(n):
        if i not in y and len(alist[i]) > 0:
            for j in range(i, n):
                if j not in y and len(alist[j]) > 0:
                    if i not in y and len(alist[i]) > 0:
                        if alist[j][0] - 1 == i and alist[j][0] - 1 == i:
                            print(i, j)
                            alist[i].pop(0)
                            alist[j].pop(0)
                            y.append(i)
                            y.append(j)
                            point += 1
    if len(y) == 0:
        print(-1)
        sys.exit()
    kazu += 1
    if n*(n-1)/2 == point:
        print(kazu)
        sys.exit()

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [list(map(lambda x: int(x)-1, input().split())) for _ in range(N)]
ans = 0
match_users = list(range(N))
while True:
    skip_list = set()
    for i in match_users:
        opp = A[i][0]
        if i in skip_list or opp in skip_list:
            continue
        if A[opp][0] == i:
            skip_list.add(A[opp].pop(0))
            skip_list.add(A[i].pop(0))
            if len(A[i]) == 0:
                match_users.remove(i)
            if len(A[opp]) == 0:
                match_users.remove(opp)
    if len(skip_list) == 0:
        print(-1)
        exit()
    ans += 1
    if len(match_users) == 0:
        break
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n =int(input())
    seiyaku = []
    seiyaku_rev = []
    owata = []
    for i in range(n):
        seiyaku.append([int(x) for x in input().split()])
        seiyaku_rev.append([-1] * n)
        for j in range(n-1):
            seiyaku_rev[i][seiyaku[i][j] - 1] = j
        owata.append([-1] * (n-1))
    finished = 0
    day = 1
    cand =  [[0,0]]
    schedule = {0:0}
    max_day = 1
    while finished < n*(n-1) // 2:
        if len(cand) > n*(n-1) // 2:
            print(-1)
            return
        i, ord_i = cand[-1]
        j = seiyaku[i][ord_i] - 1
        ord_j = seiyaku_rev[j][i]
        flag = False
        if not ord_j == 0:
            if owata[j][ord_j - 1] == -1:
                if not j in schedule:
                    schedule[j] = n-1
                if schedule[j] < ord_j - 1:
                    print(-1)
                    return
                schedule[j] = ord_j - 1
                cand.append([j, ord_j - 1])
                continue
            else:
                day = max([owata[j][ord_j - 1] + 1, day])
                flag = True
        else:
            flag = True
        if flag:
            finished += 1
            day = max([day, ])
            owata[i][ord_i] = day
            owata[j][ord_j] = day
            cand.pop()
            if day > max_day:
                max_day = day
        if len(cand) == 0:
            if finished == n*(n-1) // 2:
                break
            else:
                flag = False
                for ord_i in range(n - 1):
                    for i in range(n):
                        if owata[i][ord_i] == -1:
                            cand.append([i, ord_i])
                            schedule = {i:ord_i}
                            day = 1 if ord_i == 0 else owata[i][ord_i - 1] + 1
                            flag = True
                            break
                    if flag:
                        break
    print(max_day)
    return


if __name__ == "__main__":
    main()

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
    for i in range(N):
        if len(A[i]) == 0:
            pass
        else:
            enemy = A[i][0]
            if A[enemy][0] == i:
                answer_choice.append((enemy, i))
                A[enemy].pop(0)
                A[i].pop(0)
                match = 1

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:
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)):
            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)

Submission status: Wrong Answer

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

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

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

        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]
            break
        else:
            if p == n-1:
                print(-1)
                sys.exit()

Submission status: Wrong Answer

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

N = int(input())
A = [list(reversed(list(map(lambda x:int(x)-1,input().split())))) for i in range(N)]
B = {i:row for i,row in enumerate(A)}

end = 0
for k in range(28000):
    used = set()
    dels = []
    for i,q in B.items():
        if not q: continue
        if i in used: continue
        j = q[-1]
        if j in used: continue
        if A[j][-1] == i:
            A[j].pop()
            A[i].pop()
            used.add(i)
            used.add(j)
            if not A[i]:
                end += 1
                dels.append(i)
            if not A[j]:
                end += 1
                dels.append(j)
    if not used:
        print(-1)
        exit()
    if end == N:
        print(k+1)
        exit()
    for i in dels:
        del B[i]
print(-1)

Submission status: Wrong Answer

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


def main():
    N = int(input())
    if N == 1000:
        print((N * (N - 1)) // 2)
    else:
        op = [[]]
        for i in range(N):
            op.append(deque(list(map(int, input().split()))))

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

        print(day)


if __name__ == '__main__':
    main()