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 math
import collections
import heapq
from collections import defaultdict
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)


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

    print(n)





if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
l=[[i+1] for i in range(n)]
for i in range(n):
    l[i].append(list(map(int,input().split())))
#print(l)
sum=n*(n-1)//2
#print(sum)
c=0

day=0
for _ in range(n):
    for i in range(n):
        for j in range(i,n):
            if l[i][1] and l[j][1]:
                if l[i][1][0]==l[j][0] and l[j][1][0]==l[i][0]:
                    c+=1
                    l[i][1].remove(l[i][1][0])
                    l[j][1].remove(l[j][1][0])
    day+=1
#print(c)
for i in range(n):
    if l[i][1]!=[]:
        print(-1)
        break
else:
    print(day)

Submission status: Wrong Answer

Solution code:
# E - League
N = int(input())

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

for i in range(N):
    date += 1
    for j in range(len(A[i])):
        p1 = A[i][0]
        p2 = A[p1 - 1][0]
        if p2 == i + 1:
            A[i].pop(0)
            A[p1 - 1].pop(0)

if not A[0]:
    print(date)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
    N = int(input())
    A = [deque([int(i) - 1 for i in input().split()]) for j in range(N)]
    day = 1
    dic = [A[i][0] for i in range(N)]

    while True:
        flag = True
        flag2 = True
        for i in range(N):
            if len(A[i]) == 0:
                continue
            flag = False
            # print(flag)
            if dic[i] > i and dic[dic[i]] == i:
                flag2 = False
                tmp_i = i
                tmp_di = dic[i]
                A[tmp_i].popleft()
                A[tmp_di].popleft()
                if len(A[tmp_i]) != 0:
                    dic[tmp_i] = A[tmp_i][0]
                else:
                    dic[tmp_i] = -1
                if(len(A[tmp_di]) != 0):
                    dic[tmp_di] = A[tmp_di][0]
                else:
                    dic[tmp_di] = -1
        # print(dic)
        # print(len(A[0]), len(A[1]), len(A[2]), len(A[3]))
        # print(flag, flag2)
        if flag:
            break
        if flag2:
            day = -1
            break
        day += 1
    print(day)

main()

Submission status: Wrong Answer

Solution code:
from collections import deque

import sys
input = sys.stdin.readline


n = int(input())
a_list = {i:None for i in range(n)}
num = 0
day = 0
for i in range(n):
    a_list[i] = deque([int(i) - 1 for i in input().split()])

for kkk in range(n * (n - 1) // 2):
    visit = set([])
    day += 1
    for j in range(n):
        if j not in visit:
            try:
                if (a_list[a_list[j][0]][0] == j):
                    num += 1
                    visit.add(a_list[a_list[j][0]].popleft())
                    visit.add(a_list[j].popleft())
            except:
                continue
        if num >= n * (n - 1) // 2:
            print(day)
            exit()
    if (len(visit) == 0):
        print(-1)
        exit()
    if num >= n * (n - 1) // 2:
        print(day)
        exit()

Submission status: Wrong Answer

Solution code:
def getlist():
	return list(map(int, input().split()))

X = []
N = int(input())
for i in range(N):
	A = getlist()
	X.append([0] + A[::-1])

#日数
day = 0
while True:
	j = "No"
	check = [0] * N
	for i in range(N):
		x = X[i][-1] - 1
		if check[i] == 0 and check[x] == 0 and x != -1:
			if X[x][-1] == i + 1:
				check[i] = 1
				check[x] = 1
				X[x].pop(-1)
				X[i].pop(-1)
				j = "Yes"
	day += 1
	if j == "No":
		break

#判定
cc = "Yes"
for i in range(N):
	if X[i] != [0]:
		cc = "No"
		break

if cc == "No":
	day = -1


print(day)

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())
A = [[] for i in range(N)]
for i in range(N):
    A[i] = LI()
    A[i].reverse()
    for j in range(len(A[i])):
        A[i][j] -= 1

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

# positions = [0 for i in range(N)]
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

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

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

print(ans)

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

	while True:
		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 or target-1 not in doList:
					ind[i] += 1
					if ind[i] > N-2:
						ind[i] = -1

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

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

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

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

	print(ans)



if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
ans = 0
flag = True
while True:
    print(a)
    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: Wrong Answer

Solution code:
n = int(input())
dp = [0]*n
cnt = 0
L = []
flag = True
for i in range(n):
  T = []
  N = list(map(int,input().split()))
  for j in range(n-1):
    T.append((i+1,N[j]))
  L.append(T)
while dp != [n-1]*n:
  B = [0]*n
  act = 0
  for i in range(n):
    if B[i] == 0:
      B[i] = 1
      if dp[i] != n-1:
        miru = L[i][dp[i]][1]
        if dp[miru-1] == n-1:
          flag = False
          break
        else:
          if B[miru-1] != 1:
            if L[miru-1][dp[miru-1]][1] == i+1:
              dp[i] += 1
              dp[miru-1] += 1
              B[miru-1] = 1
              act += 1
  if act == 0:
    dp = [n-1]*n
    flag = False
  if cnt >= 10000:
    dp = [n-1]*n
    flag = False
  cnt += 1
if flag == False:
  print(-1)
else:
  print(cnt)

Submission status: Wrong Answer

Solution code:
import sys

n = int(input())
a = []
for _ in range(n):
    a.append(list(map(int, input().split())))
ans = 0
pos = [0] * n

while any([(n - 1) - x for x in pos]):
    pos_check = [False] * n
    checker = True
    for i in range(n):
        for j in range(i + 1, n):
            if pos[i] == n - 1 or pos[j] == n - 1:
                break
            if a[i][pos[i]] == j + 1 and a[j][pos[j]] == i + 1:
                pos_check[i] = True
                pos_check[j] = True
                break
    for i in range(n):
        if pos_check[i]:
            pos[i] += 1
            checker = False
    if checker:
        print(-1)
        sys.exit()
    ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = [[] for i in range(n)]
for i in range(n):
    a[i] = list(map(int, input().split()))
    
ans = 0
nowlist = [a[i][0] for i in range(n)]
ans = 0
amap = [[0 for i in range(max(0,j))] for j in range(n+1)]
dokomade = [0 for i in range(n+1)]
todaylist = []
tomorrow = []

for i in range(n):
    i1 = min(nowlist[i],i+1)
    i2 = max(nowlist[i],i+1)
    amap[i2][i1] += 1
    if(amap[i2][i1]==2):
        todaylist.append([i1,i2])

print(amap)

while(True):
    for i in range(len(todaylist)):
        i1=todaylist[i][0]
        i2=todaylist[i][1]
        dokomade[i1]+=1
        dokomade[i2]+=1
        if(dokomade[i1]<n-1):
            temp1=i1
            temp2=a[i1-1][dokomade[i1]]
            i3=max(temp1,temp2)
            i4=min(temp1,temp2)
            amap[i3][i4]+=1
            if(amap[i3][i4]==2):
                tomorrow.append([i3,i4])
        if(dokomade[i2]<n-1):
            temp1=i2
            temp2=a[i2-1][dokomade[i2]]
            i3=max(temp1,temp2)
            i4=min(temp1,temp2)
            amap[i3][i4]+=1
            if(amap[i3][i4]==2):
                tomorrow.append([i3,i4])
    
    ans += 1
    print(dokomade)
    if(len(tomorrow)==0):
        if(sum(dokomade)!= n*(n-1)):
            ans = -1
        break
    todaylist = tomorrow
    tomorrow=[]
    
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
n=int(input())
a=[list(map(int,input().split())) for i in range(n)]
now=[[0,0] for i in range(n)]
day,sumsiai=0,0
end=n*(n-1)//2
nex,minusnex=0,0
while 1:
    day+=1
    siaisuu=sumsiai
    for i in range(n):
        if now[i][0]==n-1 or now[i][1] == day:
            continue
        nex=a[i][now[i][0]]
        minusnex=nex-1
        if i+1==a[nex-1][now[minusnex][0]] and now[minusnex][1] != day:
            siaisuu+=1
            now[i][0]+=1
            now[i][1],now[minusnex][1]=day,day
            now[minusnex][0]+=1
    if siaisuu-sumsiai==0:
        print(-1)
        quit()
    if siaisuu==end:
        print(day)
        print(1)
        quit()
    sumsiai=siaisuu

Submission status: Wrong Answer

Solution code:
import sys
import collections
import copy
N = int(input())
sc = [[int(i) for i in input().split()] for i in range(N)]
count = [0] * N
done = [0] * N
fin = [N-1] * N
ans = 0
for j in range(N*(N-1)//2):
    done = [0] * N
    for i in range(N-1):
        if N-1 > count[i]:
            if done[sc[i][count[i]]-1] == 0 and done[i] == 0:
                if sc[sc[i][count[i]]-1][count[sc[i][count[i]]-1]] == i+1:
                    done[sc[i][count[i]]-1] = 1
                    done[i] = 1
                    count[sc[i][count[i]]-1] += 1
                    count[i] += 1
    ans += 1
    if done == [0] * N:
        if count == fin:
            break
        else:
            ans = -1
            break
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

N = int(input()) # < 1000

A = [0] * N
s = set()
path = defaultdict(set)
for A in range(1, N+1):
    l = [int(x) for x in input().split()]
    prev = (0, 0)
    for b in l:
        a = A
        if a > b:
            a, b = b, a
        s.add((a, b))
        path[prev].add((a, b))
        prev = a, b
TMP = 1
DONE = 2
L = []
def solve():
    status = {}
    def visit(n):
        if status[n] == TMP:
            raise Exception()
        elif status[n] is None:
            status[n] = TMP
            for m in path[n]:
                visit(m)
            status[n] = DONE
            L.append(n)
            return 1
    for p in s:
        status[p] = None
    for p in s:
        visit(p)

    heads = list(path[(0, 0)])
    d = 0
    while heads:
        d+=1
        done = [0]*(N+1)
        next = set()
        for a, b in heads:
            if done[a] or done[b]:
                next.add((a, b))
                continue
            done[a] = 1
            done[b] = 1
            for n in path[(a,b)]:
                next.add(n)
        heads = next
    return d 

try:
    print(solve())
except Exception as e:
    print(e)
    print(-1)

Submission status: Wrong Answer

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

n = int(input())
game = [0]

for _ in range(n):
    comp = list(map(int, input().split()))[::-1]
    game.append(comp)

count = 0
final = n*(n-1)//2
for day in range(1, final):
    finish = set()
    possible = False
    for me in range(1, n+1):
        if me in finish or game[me] == []:
            continue

        you = game[me][-1]
        if you in finish or game[you] == []:
            continue
        else:
            if game[you][-1] == me:
                finish.add(game[you].pop())
                finish.add(game[me].pop())
                possible = True
                count += 1
            else:
                continue

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

    if count == final:
        print(day)
        exit()

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

cal_match = (n*n-n) // 2


def all_day():
    match = [ 0 for i in range(n) ]
    day = 1
    all_day_match = 0
    stop = 0
    while stop == 0:
        new_match = 0
        for i in range(n):
            j = league[i][done[i]]
            if i != j and league[j][done[j]] == i:

                if match[i] == 1 or match[j] == 1:
                    day += 1
                    match = [ 0 for i in range(n) ]

                league[i][done[i]] = i
                league[j][done[j]] = j
                match[i] = 1
                match[j] = 1
                all_day_match += 1
                new_match += 1
                if done[i] < n-2:
                    done[i] += 1
                if done[j] < n-2:
                    done[j] += 1
        if all_day_match == cal_match:
            stop = 1
            print(day)
        if new_match == 0:
            stop = 1
            print(-1)
    return all_day_match

all_day()

Submission status: Wrong Answer

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

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
n=int(input())
a=[]
hd=[0]*n
for i in range(n):
    a.append(tuple(map(int,input().split())))
loop=0
flag=0
while(flag<n):
    stk=[]
    for i in range(n):
        if hd[i]==n-2:
            continue
        idx=a[i][hd[i]]-1
        if hd[idx]==n-2:
            print(-1)
            sys.exit()
        if a[idx][hd[idx]]==i+1:
            stk.append(i)
    if not stk:
        loop=-2
        break
    for j in stk:
        hd[j]+=1
        if hd[j]==n-2:
            flag+=1
    loop+=1
print(loop+1)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque
outs = defaultdict(list)
ins = defaultdict(int)

def get_ab(h):
    return h // 1000, h % 1000

def get_hash(a, b):
    if a >= b:
        return 1000*a + b
    else:
        return 1000*b + a
v = []
N = int(input())
for i in range(N):
    nums = list(map(int, input().split()))
    pred = get_hash(i+1, nums[0])
    v.append(pred)
    for j in range(len(nums)-1):
        now = get_hash(i+1, nums[j+1])
        v.append(now)
        outs[pred].append(now)
        ins[now] += 1
        pred = now

v = set(v)
q = deque(v1 for v1 in v 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)
if len(res) == 0:
    print(-1)
else:
    ans = 0
    before = []
    for h in res:
        a, b = get_ab(h)
        if (a in before) or (b in before):
            before = [a, b]
            ans += 1
        else:
            before.append(a)
            before.append(b)
    print(ans+1)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:

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

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

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

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

Submission status: Wrong Answer

Solution code:
def getlist():
	return list(map(int, input().split()))

X = []
N = int(input())
for i in range(N):
	A = getlist()
	X.append([0] + A[::-1])

#日数
day = 0
while True:
	j = "No"
	check = [0] * N
	for i in range(N):
		x = X[i][-1] - 1
		if check[i] == 0 and check[x] == 0 and x != -1:
			if X[x][-1] == i + 1:
				check[x] = 1
				X[x].pop(-1)
				X[i].pop(-1)
				j = "Yes"
	day += 1
	if j == "No":
		break

#判定
cc = "Yes"
for i in range(N):
	if X[i] != [0]:
		cc = "No"
		break

if cc == "No":
	day = -1


print(day)

Submission status: Wrong Answer

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

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

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

def main():
  n=I()

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

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

    for i in range(n):
      if c<=0:
        return ans

      if m[i]!=0:
        continue

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

        if a<i:
          continue

        if m[a]!=0:
          continue

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


  return ans

# main()
print(main())

Submission status: Wrong Answer

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

def main():
	n = int(input().strip())
	dqlist = [deque([-1])]
	for _ in range(n):
		v = list(map(int, input().strip().split()))
		dqlist.append(deque(v))
	day = 0
	while True:
		picked = [0] * (n+1)
		changed = False
		for i in range(1, n+1):
			if picked[i] == 1:
				continue
			if len(dqlist[i]) == 0:
				continue
			if dqlist[dqlist[i][0]][0] == i:
				# OK
				changed = True
				c = dqlist[i].popleft()
				dqlist[c].popleft()
				picked[i] = 1
				picked[c] = 1
		if changed == False:
			finFlag = True
			for i in range(1, n+1):
				if len(dqlist[i]) > 0:
					finFlag = False
			if finFlag:
				print(day+1)
				return
			else:
				print(-1)
				return
		day += 1

if __name__ == '__main__':
	main()

Submission status: Wrong Answer

Solution code:
import numpy as np
def main():
    n = int(input())
    n_list = []
    for i in range(n):
        n_list0 = list(map(int, input().split()))
        n_list.append(n_list0)
    num = [0 for _ in range(n)]
    flag = True
    days = 0
    while flag:
        flag = False
        days += 1
        fin_list = []
        for i in range(n):
            # print("@0, ", num[i], i, n, fin_list)
            if (num[i] < n-1) & (i not in fin_list):
                i_vs = n_list[i][num[i]]-1
                fin_list.append(i_vs)
                # print("@1, ", i+1, i_vs+1, n_list[i_vs][num[i_vs]])
                if i+1 == n_list[i_vs][num[i_vs]]:
                    num[i] += 1
                    num[i_vs] += 1
                    flag = True
                    # print("@2, ", num)
    flag = True
    for i in range(n):
        if num[i] != n-1:
            flag = False
            break
    if flag:
        print(days)
    else:
        print(-1)

main()

Submission status: Wrong Answer

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

n=int(input())
tf=[[False] * n for i in range(n)]
ma=[[] for i in range(n)]

for i in range(n):
    a=list(map(int, input().split()))
    d=0
    flg=False
    for val in a:
        while d < n:
            if set([i+1, val]) in ma[d]:
                d+=1
                break
            elif not tf[d][i] and not tf[d][val-1]:
                ma[d].append(set([i+1, val]))
                tf[d][i]=True
                tf[d][val-1]=True
                d+=1
                break
            if not flg:
                flg=True
            elif flg:
                print(-1)
                exit()
            d+=1

if len(ma[n-1]) == 0:
    print(n-1)
else:
    print(n)

Submission status: Wrong Answer

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

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

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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

total = N*(N-1)//2
progress = [0]*N
battled = [False]*N
any_battle = False
day = 1
for _ in range(total):
    for man in range(N):
        if progress[man] >= N-1:
            continue
        rival = A[man][progress[man]] - 1
        if battled[man] or battled[rival]:
            continue
        if A[rival][progress[rival]] - 1 == man:
            progress[man] += 1
            progress[rival] += 1
            battled[man], battled[rival] = True, True
            any_battle = True
    battled = [False]*N
    for p in progress:
        if p < N-1:
            break
    else:
        print(day)
        break
    day += 1
    if not any_battle:
        print(-1)
        break

Submission status: Wrong Answer

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

t = N * (N-1) // 2
m = [[0 for _ in range(N)] for __ in range(t+1)]

end = 0
for d in range(t):
    if end == N:
        print(d)
        break
    n = 0
    for p1 in range(N):
        i1 = m[d][p1]
        if m[d+1][p1] == i1 + 1:
            continue
        if i1 == N - 1:
            m[d+1][p1] = i1
            continue
        p2 = A[p1][i1] - 1
        if p2 < p1:
            m[d+1][p1] = i1
            continue
        i2 = m[d][p2]
        if i2 == N - 1:
            m[d+1][p1] = i1
            continue
        if m[d+1][p2] == i2 + 1:
            m[d+1][p1] = i1
            continue
        if A[p2][i2] - 1 == p1:
            m[d+1][p1] = i1 + 1
            if i1 + 1 == N - 1:
                end += 1
            m[d+1][p2] = i2 + 1
            if i2 + 1 == N - 1:
                end += 1
            n += 1
    if n == 0:
        print(-1)
        break
else:
    print(t)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
n=int(input())
a=[]
for _ in range(n):
  a.append(list(map(int, input().split(' '))))

cur_match = []
total = 0
count = 0
while total < n*(n-1):
  count += 1
  for i in range(n):
    if i not in cur_match and len(a[i]) > 0:
      cand = a[i][0]-1
      if cand not in cur_match and len(a[cand]) > 0 and a[cand][0]-1 == i:
        print(cand, i)
        cur_match.extend([cand, i])
        a[cand].pop(0)
        a[i].pop(0)
  if len(cur_match) == 0:
    print('-1')
    sys.exit(0)
  else:
    total += len(cur_match)
  cur_match = []
print(count)

Submission status: Wrong Answer

Solution code:
n=int(input())
league=[tuple(map(int,input().split())) for _ in range(n)]
order=[0]*n

total_match=n*(n-1)//2
match=0
day=0

for _ in range(total_match):
    day+=1
    today_match=[]

    for i in range(n):
        if not i in today_match and order[i]<n-1:
            m=league[i][order[i]]-1
        if not m in today_match and order[m]<n-1 and league[m][order[m]]-1==i:
            today_match.append(i)
            today_match.append(m)
            order[i]+=1
            order[m]+=1
    if not today_match:
        day=-1
        break
    match+=len(today_match)//2
    if match>=total_match:
        break

print(day)

Submission status: Wrong Answer

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

output = 1
memo = [0] * N
newmemo = [0] * N
owari = [0] * N
flag = 0
while flag < N:
    ng = 0
    for i in range(N):
        check = A[i][memo[i]]-1
        if i==A[check][memo[check]]-1:
            if memo[i] < N-2:
                newmemo[i]+=1
            elif (memo[i] == N-2) and (owari[i]==0):
                owari[i] = 1
                flag += 1
            elif (memo[i] == N-2) and (owari[i]==1):
                continue
        else:
            ng += 1
    if ng == N:
        output = -1
        break
    memo = newmemo[:]
    output += 1
    flag += 1

print(output)