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: Runtime Error

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
allpc = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[aite].appendleft(aiteaite)
      else:
        dic[i].appendleft(aite)

  if playcount > 0:
    ans += 1
  else:
    break

if allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque


def p_e():
    N = int(input())
    A = [deque(map(lambda x: x - 1, map(int, input().split()))) for _ in range(N)]

    ans = 0
    while True:
        idx = []
        l = list(range(N))

        for i in l:
            if not A[i]:
                continue

            if i == A[A[i][0]][0]:
                idx.append(i)
                l.pop(A[i])

        if not idx:
            break

        for i in idx:
            A[i].popleft()
        ans += 1

    for a in A:
        if a:
            print(-1)
            exit()

    print(ans)


if __name__ == '__main__':
    p_e()

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
input=sys.stdin.readline
def main():
  a=int(input())
  b=[[]for i in range(a)]
  for i in range(a):
    b[i]=deque(list(map(int,input().split())))
  c=[[]for i in range(a)]
  ans=0
  d=[0 for i in range(a)]
  while sum(len(v) for v in b)!=0:
    f=[0 for i in range(a)]
    ans+=1
    T=0
    for i in range(a):
      if d[i]==0 and f[i]==0 or len(b[i])>0:
        e=b[i][0]-1
        if e in c[i]:
          c[i].pop(c[i].index(e))
          T=1
          b[e].popleft()
          b[i].popleft()
          d[i]=0
          d[e]=0
          f[i]=1
          f[e]=1
        else:
          c[e].append(i)
          d[i]=1
    if T==0:
      print(-1)
      exit()
      
      
  print(ans)  
if __name__ == '__main__':  
  main()

Submission status: Runtime Error

Solution code:
from collections import deque

N = int(input())
Ass = deque(deque(map(int, input().split())) for _ in range(N))

dp = [0 for _ in range(N)]
index = [0 for _ in range(N)]
flag = True
while flag:
    flag = False
    for i, As in enumerate(Ass):
        if not As:
            continue
        t = As[index[i]] - 1
        if Ass[t][index[t]] == i + 1:
            index[t] += 1
            index[i] += 1
            dp[t] = dp[i] = max(dp[t], dp[i]) + 1
            flag = True
if any(Ass):
    print(-1)
else:
    print(max(dp))

Submission status: Runtime Error

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

memo=[1 for i in range(N)]
ans=[]
    
def d(i,loop):
    if len(A[i])>0:

        j=A[i][0]-1
        if i==A[j][0]-1:
            A[i].popleft()
            A[j].popleft()
            if memo[i]==1:
                ans.append(1)
                memo[i]-=1
            else:
                memo[i]+=1
            if memo[j]==1:

                memo[j]-=1
            else:
                memo[j]+=1

                

        else:
            return d(j,loop)
        
    elif loop==N-1:
        return 
    else:
        loop+=1
        return d(i+1,loop)

for ii in range(N*(N-1)//2):
    d(0,0)

check=0
for a in A:
    check+=len(a)
if check==0:
    print(sum(ans))
else:
    print(-1)

Submission status: Runtime Error

Solution code:

from copy import deepcopy
N=int(input())

A=[[int(i) for i in input().split()] for _ in range(N)]
l=[0 for _ in range(N)]
ll=[0 for _ in range(N)]
day=0
while True:
    if min(l)==N-1:
        can=True
        break
    can=False
    for i in [j-1 for j, i in enumerate(l) if l[i]!=N-1 ]:
        if l[i]==N-1:
            continue
        j=A[i][l[i]]-1
        if A[j][l[j]]-1==i:
            ll[i]+=1
            can=True
    l=deepcopy(ll)
    if can==False:
        break
    day+=1
if can==False:
    print(-1)
if can==True:
    print(day)

Submission status: Runtime Error

Solution code:
n=int(input())
a=[list(map(int,input().split()))for i in range(n)]
s=[0 for i in range(n)]
p=0
r=0
d=0
while r<n:
    t=[0]*n
    d+=1
    l=0
    
    for i in range(n):
        if s[i]<n:
            if t[i]==0 and t[a[i][s[i]]]==0:
                if a[i][s[i]]==i+1:
                    l=1
                    t[i]=1
                    t[a[i][s[i]]]=1
                    p=a[i][s[i]]
                    s[p]+=1
                    s[i]+=1
                    if s[p]==n-1:
                        r+=1
                    if s[i]==n-1:
                        r+=1
    if l==1:
        print(-1)
        break
else:
    print(d)

Submission status: Runtime Error

Solution code:
def search(can):
    day = 0
    while True:
        # matchの候補をリスト化
        match = []
        for i in range(N):
            if can[can[i]] == i:
                match.append((i, can[i]))

        if len(match) == 0:
            return -1

        # 可能なmatchの組み合わせで試していく
        for i in range(1 << len(match)):
            player = [0] * N
            flag = True
            for j in range(len(match)):
                if i >> j & 1 == 1:
                    if player[i] or player[i]:
                        flag = False
                        break
                    player[i] = player[j] = 1
                if flag:
                    # matchを行う
                    for i, p in enumerate(player):
                        if p:
                            consumed[i] += 1
                            if consumed[i] != N:
                                can[i] = A[i][consumed[i]]
                    day += 1

        if sum(consumed) == N * (N-1):
            return day


if __name__ == '__main__':
    N = int(input())
    A = [[int(x)-1 for x in input().split()] for _ in range(N)]

    # 初期化
    can = dict()
    consumed = [0] * N
    for i in range(N):
        can[i] = A[i][0]

    print(search(can))
    print()

Submission status: Runtime Error

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)
                else:
                    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: Runtime Error

Solution code:
N=int(input())
a=[]
b=[]
c=[0]*N
cnt=0
for i in range(N):
  a.append(list(map(int, input().split())))
  a[i].append(i+1)
print(a)

for i in range(N):
  b.append(a[i][0])
print(b)
for j in range(N*(N-1)//2):
  for i in range(N):
    if i==b[b[i]-1]-1:
      c[i]+=1
      c[b[i]-1]+=1
  print(c)
  for i in range(N):
    b[i]=a[i][c[i]//2]
  print(b)
  cnt+=1
print('-1')

Submission status: Runtime Error

Solution code:
n = int(input())
a = []
for _ in range(n):
    a.append(list(map(int, input().split())))
    
for i in range(n):
    b = a[i][:]
    b.sort()
    cnt = 0
    for j in range(n-1):
        if a[b[j]][i] < a[b[j]+1][i]:
            continue
        elif a[b[j]][i] == a[b[j]+1][i]:
            cnt += 1
            continue
        else:
            ans = -1
            break
    if ans == -1:
        break
    
if ans == -1:
    print(ans)
else:
    print(cnt)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys

N = int(input())
As = [list(map(int,input().split())) for i in range(N)]
As = np.array(As)-1


current_waitings = As[:,0]
game_counter = np.zeros(N).astype('int')

day = 0
completed_players = []
day_player = []
for x in range(N*(N+1)//2):
    day_player = []
    for i,e1 in enumerate(current_waitings):
        if i in completed_players:
            continue
        if current_waitings[e1] == i and e1 not in day_player and i not in day_player:
            day_player.append(i)
            day_player.append(e1)
            if game_counter[i] == N-2:
                completed_players.append(i)
            if game_counter[i] <= N-3:
                game_counter[i] += 1
            if game_counter[e1] == N-2:
                completed_players.append(e1)
            if game_counter[e1] <= N-3:
                game_counter[e1] += 1
            current_waitings[i] = As[i][game_counter[i]]
            current_waitings[e1] = As[e1][game_counter[e1]]
        if len(completed_players) == N:
            print(day+1)
            sys.exit()
    day += 1
print(-1)

Submission status: Runtime Error

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: Runtime Error

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
allpc = 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].popleft()
      if aite not in tmpset:
        aiteaite = dic[aite].popleft()
        if aiteaite == i:
          tmpset.add(i)
          tmpset.add(aite)
          playcount += 1
          allpc += 1
        else:
          dic[aite].appendleft(aiteaite)
      else:
          dic[i].appendleft(aite)

  if playcount > 0:
    ans += 1
  else:
    break

if allpc != int(N * (N-1) /2):
  print(-1)
else:
  print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
A = []
for i in range(N):
    A.append([])
for i in range(N):
    input_str_list = input().split(" ")
    for j in range(N-1):
        A[i].append(int(input_str_list[j]))

flag = 1
length_flag = 0
count = 0
for i in range(N*(N-1)/2):
    the_set = set([])
    for i in range(N):
        if len(A[i]) > 0:
            length_flag = 1
            if i == A[A[i][0]][0]:
                the_set.add(i)
                the_set.add(A[i])
                flag = 0

    if flag == 1:
        break;
    
    for j in the_set:
        A[j].pop(0)

    

    if length_flag == 0:
        break;

    count += 1

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

Submission status: Runtime Error

Solution code:
num_player = int(input())
table = [{i: int(x)-1 for i, x in enumerate(input().split(' ') + [str(num_player)])} for _ in range(0, num_player)]
# print(table)

ptr = [0 for _ in range(0, num_player)]

count = 0
available = set(range(0, num_player))

while min(ptr) != num_player-1:
    count += 1
    blocker = set()
    for i in available:
        target = table[i][ptr[i]]
        if target > i:
            continue
        if target not in available:
            continue
        if target == num_player:
            available.remove(target)
            continue
        if table[target][ptr[target]] == i:
            if target in blocker or i in blocker:
                continue
            ptr[i] += 1
            ptr[target] += 1
            blocker.add(i)
            blocker.add(target)
    if not blocker:
        print(-1)
        exit(0)

print(count)
exit(0)

Submission status: Runtime Error

Solution code:
n=int(input())
a=[list(map(int,input().split()))for i in range(n)]
s=[0 for i in range(n)]
p=0
r=0
d=0
while r<n:
    t=[0]*n
    d+=1
    l=0
    for i in range(n):
        if s[i]<n:
            if t[i]==0 and t[a[i][s[i]]]==0:
                if a[i][s[i]]==i+1:
                    l=1
                    t[i]=1
                    t[a[i][s[i]]]=1
                    p=a[i][s[i]]
                    s[p]+=1
                    s[i]+=1
                    if s[p]==n:
                        r+=1
                    if s[i]==n:
                        r+=1
    if l==1:
        print(-1)
        break
else:
    print(d)

Submission status: Runtime Error

Solution code:
from collections import deque


def p_e():
    N = int(input())
    A = [deque(map(lambda x: x - 1, map(int, input().split()))) for _ in range(N)]

    ans = 0
    while True:
        idx = []
        l = list(range(N))

        for i in l:
            if not A[i]:
                continue

            if i == A[A[i][0]][0]:
                idx.append(i)
                l.pop(A[A[i][0]][0])

        if not idx:
            break

        for i in idx:
            A[i].popleft()
        ans += 1

    for a in A:
        if a:
            print(-1)
            exit()

    print(ans)


if __name__ == '__main__':
    p_e()

Submission status: Runtime Error

Solution code:
n=int(input)
a=[list(map(int,input().split()))for i in range(n)]
s=[0 for i in range(n)]
p=0
r=0
d=0
while r<n:
    t=[0]*n
    d+=1
    l=0
    for i in range(n):
        if s[i]<n:
            if t[i]==0 and t[a[i][s[i]]]==0:
                if a[i][s[i]]==i+1:
                    l=1
                    t[i]=1
                    t[a[i][s[i]]]=1
                    p=a[i][s[i]]
                    s[p]+=1
                    s[i]+=1
                    if s[p]==n:
                        r+=1
                    if s[i]==n:
                        r+=1
    if l==1:
        print(-1)
        break
else:
    print(d)

Submission status: Runtime Error

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools, os, pdb
sys.setrecursionlimit(10**7)
from fractions import Fraction
inf = 10 ** 20
eps = 1.0 / 10**10
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 LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def _I(): return int(sys.stdin.readline())
def _F(): return float(sys.stdin.readline())
def _pf(s): return print(s, flush=True)
def perr(s): return print(s, file=sys.stderr)

def main():
    A_list = []
    if 'LOCAL' in os.environ:
        N = 1000
        for i in range(N):
            tmp = [j for j in range(N) if i != j]
            random.shuffle(tmp)
            A_list.append(tmp)

    else:
        N = _I()
        A_list = [LI() for i in range(N)]
        #  for i in range(N):
        #      A_list.append(LI())
        #  perr(A_list)
    new_A_list = {}
    for aidx, A in enumerate(A_list):
        new_A_list[aidx] = tuple(i-1 for i in A)
    A_list = new_A_list

    """
    まず、N=1000までなので、
    1000*1000=10**6まである。
    試合の日数を最小かする。
    つまりできるだけ効率よく1日に試合を詰め込むことを考える
    そもそも1のところに2とあったら、
    全通りを求めると？
    どの試合にするかで1000*999/2の階乗=10**6/2の階乗通りある
    まず選手iの1つ目を見ていく
    その相手のところをみて、current_idxがiだったら試合可能

    """

    current_opponent_idx = None
    current_day = 0
    is_ok = False
    # 各選手の試合状況
    current_position_list = {i:0 for i in range(N)}
    done_player_list = {}
    position_sum = 0
    done_sum = (N-1)*N
    #  all_done_players = set()
    N_1 = N - 1
    for _ in range(10**7):
        #  print('day: ', current_day)
        #  print('current position list', current_position_list)
        #  pdb.set_trace()
        is_ok = False
        #  if all(position == N-1 for position in current_position_list):
        if position_sum == done_sum:
            # 全試合終了
            break

        for i in range(N_1):
            #  print('--- in for---- current position list', current_position_list)
            # 選手iが試合できるか見る
            if done_player_list.get(i):
                continue

            #  if i in all_done_players:
            if current_position_list.get(i) == N-1:
                # この選手はすべての試合を終了している
                continue

            # iの試合相手のidx
            opponent_idx = A_list.get(i)[current_position_list.get(i)]
            if done_player_list.get(opponent_idx):
                # 試合相手がすでに今日試合してた場合
                continue

            #  print('i', i)
            #  print('opponent', opponent_idx)

            # iの試合相手の次の相手が選手iなら成立する
            if A_listget(opponent_idx)[current_position_listget(opponent_idx)] == i:
                #  print('試合した', i, opponent_idx)
                # 試合可能
                #  done_player_list.extend([i, opponent_idx])
                #  done_player_list += (opponent_idx, i)
                done_player_list[i] = True
                #  done_player_list.add(opponent_idx)
                done_player_list[opponent_idx] = True
                current_position_list[i] += 1
                current_position_list[opponent_idx] += 1
                #  if current_position_list[i] == N-1:
                #      all_done_players.add(i)
                #  if current_position_list[opponent_idx] == N-1:
                #      all_done_players.add(opponent_idx)
                position_sum += 2
                # 試合がまだ可能であるというフラグをつける
                is_ok = True

        if not is_ok:
            # 1試合も成立しなかったらストップする
            print(-1)
            exit()

        done_player_list = {}
        current_day += 1

    print(current_day)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N = int(input())
A = [0]
for i in range(1,N+1):
    A.append([int(x) for x in input().split()] + [0])

date = 0
match = 0
OK = True
while match < N*(N-1)//2:
    temp = set()
    for i in range(1,N):
        j = A[i][0]
        if A[j][0] == i:
            if j > i:
                temp.add(i)
                temp.add(j)
                match += 1
    if temp == set():
        OK = False
        break
    for i in temp:
        A[i].pop(0)
    date += 1

if OK:  print(date)
else: print(-1)

Submission status: Runtime Error

Solution code:
import sys,collections as cl,bisect as bs,copy
sys.setrecursionlimit(100000)
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return k
    else:
        return False

n = onem()

on = []
wh = [[-1 for j in range(n)] for i in range(n)]
de = cl.deque()
for i in range(n):
    k = l()
    for j in range(n-1):
        k[j] -= 1
    k.reverse()
    de.append([k[0],i])
    on.append(cl.deque(k))


co = 0
ddd = cl.deque()
while True:
    ddd.clear()
    co += 1
    cl = [1 for i in range(n)]
    
    while de:
        kkk = de.popleft()
        if on[kkk[0]][0] == kkk[1] and cl[kkk[0]] and cl[kkk[1]]:
            cl[kkk[0]] = 0
            cl[kkk[1]] = 0
            on[kkk[0]].popleft()
            on[kkk[1]].popleft()
            if len(on[kkk[1]]) != 0:
                ddd.append([on[kkk[1]][0],kkk[1]])
            if len(on[kkk[0]]) != 0:
                ddd.append([on[kkk[0]][0],kkk[0]])
    de = copy.deepcopy(ddd)
    
    if sum(cl) == n:
        co = -1
        break
    elif len(de) == 0:
        break

print(co)

Submission status: Runtime Error

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
                status.remove(enemy)

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: Runtime Error

Solution code:
N = int(input())

A = []

for _ in range(N):
	A.append(list(map(int, input().split())))
	

	
played_flg = 1
day = 0
played_game = 0
need_ game = N * (N - 1) / 2

while played_flg:
	played_flg = 0
	day += 1
	game_played = [False for _ in range(N)]
	for i in range(N):
		# print(game_played)
		if len(A[i]) != 0 and A[A[i][0] - 1][0] - 1 == i: 
			if game_played[A[i][0] - 1] == False:
				if game_played[i] == False:
					# print(i, A[i][0] - 1)
					game_played[A[i][0] - 1], game_played[i] = True, True
					played_flg = 1
					played_game += 1
					A[A[i][0] - 1].pop(0)
					A[i].pop(0)
	if played_game == need_game:
		break

if played_flg == 0:
	print(-1)
else:
	print(day)

Submission status: Runtime Error

Solution code:
import sys
n=int(input())
lst=[]
days=0
for i in range(n):
  lst.append(list(map(int,input().split())))
for j in range(n-1):
  if all(set(list(k+1,lst[k][j]))!=set(list(lst[k][j],lst[lst[k][j]][j])) for k in range(n)):
    print('-1')
    sys.exit()
  for k in range(n):
    if lst[k:k+1]:
      if lst[k][j:j+1]:
        if set(list(k+1,lst[k][j]))==set(list(lst[k][j],lst[lst[k][j]][j])):
          lst[k].remove(lst[k][j])
          lst[lst[k][j]].remove(lst[lst[k][j]][j])
  days+=1    
print(days)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
from collections import deque
def map_all(es):
    return all([e == es[0] for e in es[1:]]) if es else False

if __name__ == '__main__':
    N = int(input())
    A = [deque(map(int, input().split())) for i in range(N)]
    member = list(range(N))
    today = []
    flag=False
    
    for d in range(N*(N-1)//2):
        for me in member:
            if len(A[me-1]) != 0:
                opp = A[me-1][0]
                if A[opp-1][0] == me:
                    today.append(me)


        for n in today:
            A[n-1].popleft()
            if len(A[n-1]) == 0:
                member.remove(n-1)
        today = []
        
        if len(member)==0: #map_all(A):
            flag=True
            break
    if flag:
        print(d+1)
    else:
        print(-1)

Submission status: Runtime Error

Solution code:
import time
from collections import deque
tstart=time.time()
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 False
    else:
        return True
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]
tfin=time.time()
if tfin-tstart<1:
    print([0,0][3])
print(dp[-1])

Submission status: Runtime Error

Solution code:
n=int(input())
l=[]
for i in range(n):
  l1=list(map(int,input().split()))
  l.append(l1)
b=True
day=0
lcount=[0 for i in range(n+1)]
lcount[0]=n-1
while b and min(lcount)!=n-1:
  day+=1
  todaygame=[1 for i in range(n+1)]
  for i in range(1,n+1):
    if lcount[i]==-1+n:
      pass
    elif lcount[l[i][lcount[i]]]==-1+n:
      pass
    else:
      j=l[i][lcount[i]]
      if l[j][lcount[j]]==i:
        if todaygame[i]==1  and todaygame[j]==1:
          todaygame[i]=0
          todaygame[j]=0
                           
          lcount[i]+=1
          lcount[j]+=1
                         
  if todaygame==[1 for i in range(n+1)]:
    b=False
  else:
    todaygame=[1 for i in range(n+1)]
if b:
  print(day)
else:
  print(-1)

Submission status: Runtime Error

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