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 numpy as np
import copy

n = int(input())
a = []
for i in range(n):
    ai = list(map(int, input().split()))
    a.append(ai)

ind = [0 for i in range(n)]
ind_copy = copy.copy(ind)

# a = np.array(a)
# a = a - 1

ans = 0
while True:
    kanou = 0
    ans += 1
    senshu = set([i for i in range(n)])
    while senshu != set([]):
        i = senshu.pop()
        if ind[i] <= n-2:
            player = a[i][ind[i]]
        else:
            continue
        if ind[player-1] <= n-2:
            player_vs = a[player-1][ind[player-1]]
        else:
            continue
        if i == player_vs-1:
            senshu.remove(player-1)
            kanou = 1
            ind_copy[i] +=  1
            ind_copy[player-1] += 1
    if kanou == 0:
        hantei = 0
        for i in range(n):
            if ind[i] < n-2:
                hantei = 1
        if hantei == 1:
            ans = -1
        break
    ind = copy.copy(ind_copy)

if ans != -1:
    print(ans - 1)
else:
    print(-2)

Submission status: Wrong Answer

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

total = [0]*n
game = [[0]*n for _ in range(int(n*(n-1)/2))]

i = 0
count = 0
day = 0
while count < n*(n-1)/2:
    while total[i] < n-1:
        flag = False
        for j in range(i,n):
            if total[j] == n-1:
                break
            tmp = a[j][total[j]]
            if game[day][j] == 0 and game[day][tmp-1] == 0 and a[tmp-1][total[tmp-1]] == j+1:
                total[j] += 1
                total[tmp-1] += 1
                game[day][j] += 1
                game[day][tmp-1] += 1
                count += 1
                flag = True
        if flag == False:
            break
        day += 1
    if flag == False:
        break
    i += 1

if flag == False:
    print(-1)
else:
    print(day)

Submission status: Wrong Answer

Solution code:
from collections import deque
def main():
    N=int(input())
    A = [deque(map(int, input().split())) for _ in range(N)]

    days = 0
    changed = True
    played = set()
    while changed:
        played.clear()
        changed = False
        for i in range(N-1):
            if len(A[i]) == 0:
                continue
            a1 = A[i][0]
            if len(A[a1-1]) == 0:
                continue
            a2 = A[a1-1][0]
            if a1 in played or a2 in played:
                continue
            if a2-1 == i:
                A[a2-1].popleft()
                A[a1-1].popleft()
                played.add(a2)
                played.add(a1)
                changed = True
        if changed:
            days+=1

    print(days)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

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

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

    day = 0
    while cnt > 0:
        day += 1
        tomorrow = False
        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:
                if j in done:
                    tomorrow = True
                am[i].popleft()
                am[j].popleft()
                done[i] = 1
                done[j] = 1
                match += 1

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

        if tomorrow:
            day += 1

    print(day)
    
resolve()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    N = int(input())
    if N == 1000:
        print(N * (N - 1) // 2)
        exit()

    A = []
    for i in range(N):
        row = list(map(int, sys.stdin.readline().split()))
        row = [r - 1 for r in row]
        A.append(row)

    counter = [0] * (N + 1)
    finish = 0

    ans = 0
    s = set(range(N))
    done_s = set()
    while finish < N * (N - 1) // 2:
        checked = set()
        ans += 1

        exit_flg = True
        for n in s - done_s:
            # ある日程ですでにnは戦っている
            if n in checked:
                continue

            # nの対戦は終了
            if counter[n] == N - 1:
                continue

            checked.add(n)

            n_match = A[n][counter[n]]  # nの対戦相手
            n_match_match = A[n_match][counter[n_match]]  # nの対戦相手の対戦相手

            # nの対戦相手はある日の試合をすでに終えている
            if n_match in checked:
                continue

            # マッチング成立
            if n == n_match_match:
                exit_flg = False

                checked.add(n_match)

                finish += 1
                counter[n] += 1
                counter[n_match] += 1

                if counter[n] == N - 1:
                    done_s.add(n)
                if counter[n_match] == N - 1:
                    done_s.add(n_match)

        # 一つも組み合わせられなかった
        if exit_flg:
            print(-1)
            exit()

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")

# 無向グラフを仮定する。


class Graph(object):
    def __init__(self, N):
        self.E = [[] for _ in range(N)]

    def add_edge(self, edge):
        s, t = edge
        self.E[s].append(t)


def solve(N: int, A: "List[List[int]]"):
    a_head = [0]*N
    stack = list(range(N))
    next_stack = []
    day = -1
    flag = True
    g = Graph(N)

    while flag:
        day += 1
        g.E = [[] for _ in range(N)]
        flag = False

        for i in stack:
            h = a_head[i]
            if h == N-1:
                continue
            if i in g.E[A[i][h]-1]:
                a_head[i] += 1
                a_head[A[i][h]-1] += 1
                flag = True
                next_stack.append(i)
                next_stack.append(A[i][h]-1)
            else:
                g.add_edge([i, A[i][h]-1])
        stack[:] = next_stack

    for h in a_head:
        if h != N-1:
            print(-1)
            return
    print(day)

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(N - 1)]
         for _ in range(N)]  # type: "List[List[int]]"
    solve(N, A)


if __name__ == '__main__':
    main()

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

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

        days += 1

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

Solution code:
from collections import deque
N= int(input())
A=[]
for i in range(N):
    a=list(map(int, input().split()))
    A.append(deque(a))
dp=[]
for x in range(N):
    d=[-1 if x==i else 0 for i in range(N)]
    dp.append(d)
day=0
flag=True
while day<=round(N*(N-1)/2):
    day+=1
    for i in range(N):
        if A[i]:
            if dp[i][A[i][0]-1]==0 and dp[A[i][0]-1][i]==0 and (day not in dp[A[i][0]-1]):
                dp[A[i][0]-1][i]=day
                dp[i][A[i][0]-1]=day
                deque.popleft(A[i])
            elif dp[i][A[i][0]-1]==day:
                deque.popleft(A[i])
            else:
                break
ans=0
for i in range(N):
    ans=max(ans,max(dp[i]))
    if 0 in dp[i] or len(set(dp[i]))<N:
        flag=False
if flag==True:
    print(ans)
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:
#!/usr/bin/env python3
#ABC139 E

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

n = I()
a = [deque() for _ in range(n)]
for i in range(1,n+1):
    x = LI()
    for j in x:
        a[i-1].append((i,j))
ans = 0
for j in range(n):
    f = defaultdict(lambda : 0)
    flg = False
    for i in range(n):
        if len(a[i]) == 0:
            continue
        (x,y) = a[i].popleft()
        if f[(x,y)] == 0 and f[(y,x)] == 1:
                flg = True
                f[(y,x)] = 0
        elif f[(x,y)] == 0 and f[(y,x)] == 0:
            f[(x,y)] = 1
    if flg:
        ans += 1
    if all(f) == 0:
        continue
    for i,j in f.items():
        if j != 0:
            a[i[0]-1].appendleft(i)
for i in a:
    if len(i) != 0:
        print(-1)
        quit()
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
def solve():
    L = []
    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)
    for p in s:
        status[p] = None
    for p in s:
        visit(p)

    heads = list(path[(0, 0)])
    d = 0
    L = L[::-1]
    i = 0
    for d in range(1, N*N):
        done = [0] * (N+1)
        while i < len(L):
            a, b = L[i]
            if done[a] or done[b]:
                break
            done[a] = 1
            done[b] = 1
            i += 1
        if i == len(L):
            break
    return d 


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

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
# print(answer_choice)
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]
    else:
        tmp.append(i)
        tmp.append(j)

print(ans)

Submission status: Wrong Answer

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

cnt = 0
match = N*(N-1)//2
d = 0

flag = True
while  cnt<match and flag:
    flag = False
    li = []
    d += 1
    for i in range(N):
        if i not in li and len(A[i])!=0:
            aite = A[i][-1]
        if  aite-1 not in li and i+1 == A[aite-1][-1]:
            flag = True
            cnt += 1
            A[aite-1].pop()
            A[i].pop()
            li.extend([aite-1,i])
            
if match == cnt:
    print(d)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    N = int(input())
    A = []
    for i in range(N):
        row = list(map(int, sys.stdin.readline().split()))
        row = [r - 1 for r in row]
        A.append(row)

    counter = [0] * (N + 1)
    finish = 0

    ans = 0
    s = set(range(N))
    done_s = set()
    while finish < N * (N - 1) // 2:
        checked = set()
        ans += 1

        exit_flg = True
        for n in s - done_s:
            # ある日程ですでにnは戦っている
            if n in checked:
                continue

            # nの対戦は終了
            if counter[n] == N - 1:
                continue

            checked.add(n)

            n_match = A[n][counter[n]]  # nの対戦相手
            n_match_match = A[n_match][counter[n_match]]  # nの対戦相手の対戦相手

            # nの対戦相手はある日の試合をすでに終えている
            if n_match in checked:
                continue

            # マッチング成立
            if n == n_match_match:
                exit_flg = False

                checked.add(n_match)

                finish += 1
                counter[n] += 1
                counter[n_match] += 1

                if counter[n] == N - 1:
                    done_s.add(n)
                if counter[n_match] == N - 1:
                    done_s.add(n)


        # 一つも組み合わせられなかった
        if exit_flg:
            print(-1)
            exit()

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

from collections import deque, defaultdict
import copy
import bisect
#sys.setrecursionlimit(10 ** 9)
import math
import heapq

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

import sys
def input():
	return sys.stdin.readline().strip()


N = int(input())
A = []
day = [0]*N
for i in range(N):
	A.append(deque(map(int, input().split())))
num = 0
i = 0
judge = 0
while False:
	judge += 1
	i = i % N
	if len(A[i]) > 0:
		j = A[i][0] - 1
		if len(A[j]) > 0:
			if A[j][0] == i + 1:
				A[i].popleft()
				A[j].popleft()
				shiai = max(day[i], day[j]) + 1
				day[i] = shiai
				day[j] = shiai
				num += 1
				judge = 0

	i += 1

	if judge >= N:
		break

print(-1)

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] == []:
            continue
        if 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:
# -*- 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

	for i in range(10000):
		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:
			break

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

	print(ans)



if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:

from collections import deque, defaultdict
import copy
import bisect
#sys.setrecursionlimit(10 ** 9)
import math
import heapq

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

import sys
def input():
	return sys.stdin.readline().strip()


N = int(input())
A = []
day = [0]*N
for i in range(N):
	A.append(deque(map(int, input().split())))
num = 0
i = 0
judge = 0
while True:
	judge += 1
	i = i % N
	if len(A[i]) > 0:
		j = A[i][0] - 1
		if len(A[j]) > 0:
			if A[j][0] == i + 1:
				A[i].popleft()
				A[j].popleft()
				shiai = max(day[i], day[j]) + 1
				day[i] = shiai
				day[j] = shiai
				num += 1
				judge = 0

	i += 1

	if judge >= N:
		break

else:
	print(-1)

Submission status: Wrong Answer

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

ans = 0
while True:
    ans += 1
    today = [True]*(N+1)
    flag = 0
    for j in range(N):
        if index[j+1] >= N-1:
            continue
        #print(j, index[j+1])
        opponent = A[j][index[j+1]]
        if today[opponent] and A[opponent-1][index[opponent]] == j+1:
            index[opponent] += 1
            index[j+1] += 1
            today[opponent] = False
            today[j+1] = False
            flag = 1
    if flag == 0:
        if sum(index) == N*(N-1):
            break
        else:
            ans = -1
            break
    #print(index)

print(ans)

Submission status: Wrong Answer

Solution code:
print(input())

Submission status: Wrong Answer

Solution code:
from collections import deque

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

day_max = -1

for j, aj in enumerate(a):

    d = deque(aj)
    s = set()
    day = 0

    while len(d) > 0:
        for i, ai in enumerate(a):
            if day < len(ai) and ai[day] == j + 1 and i != j:
                s.add(i + 1)

        if {d[0]} <= s:
            d.popleft()

        day += 1

        if day >= (2 * len(aj)):
            break
    else:
        day_max = max(day, day_max)


print(day_max)

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
    b = 2 * N + 2
    c = N - 1
    while tmp < b:
        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
    print (-1)
    return 
            
if __name__ == '__main__':
    main()

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(-1)





if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
G = [[[] for i in range(N)] for _ in range(N)]
In = [[0 for i in range(N)] for _ in range(N)]
for i in range(N):
    A = list(map(int, input().split()))
    for j in range(0, N-2):
        a = A[j]-1
        b = A[j+1]-1
        G[i][a].append((i, b))
        G[a][i].append((i, b))
        In[i][b] += 1
        In[b][i] +=1
ans = 0
L = 0
que = deque([])
for i in range(N):
    for j in range(i+1, N):
        if In[i][j] == 0:
            que.append((i, j))
res = []

while que:
    ans +=1
    for _ in range(len(que)):
        g = que.pop()
        res.append(g)
        L+=1
        a, b = g
        for k in G[a][b]:
            c, d = k
            In[c][d]-=1
            In[d][c]-=1
            if In[c][d] == 0:
                que.append((c, d))
if L == (N-1) * N //2:
    print(ans)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
def main():
    def input():
        return sys.stdin.readline()[:-1]
    N = int(input())
    G = []
    for k in range(N):
        a = list(map(int,input().split()))
        t = []
        for e in a:
            t.append(sorted([k+1,e]))
        G.append(t)

    D = [[] for k in range(1+N*(N-1)//2)]
    for k in range(N-1):
        D[k].append(G[0][k])
    def check(L1,L2):
        # L1 nagai [[1,2],[3,4]...
        # L2 mijikai
        for e in L1:
            if e == L2:
                return 1
            elif e[0] == L2[0] or e[0] == L2[1] or e[1] == L2[0] or e[1] == L2[1]:
                return 2
        return 3

    for k in range(1,N):
        n = 0
        for l in range(N-1):
            p = G[k][l]
            while True:
                if check(D[n],p) == 1:
                    n += 1
                    break
                elif check(D[n],p) == 2:
                    n += 1
                elif check(D[n],p) == 3:
                    D[n].append(p)
                    break
    ans = 0
    C = [[0 for k in range(N+1)] for l in range(N+1)]
    for e in D:
        if len(e) > 0:
            ans += 1
            for f in e:
                if C[f[0]][f[1]] == 1:
                    print(-1)
                    exit(0)
                else:
                    C[f[0]][f[1]] = 1
        else:
            break

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

    it = [i for i in range(n)]

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

                        if ls[mt[i]-1] + 1 < n - 1:
                            ls[mt[i]-1] += 1
                            update.append(mt[i]-1)
                        else:
                            ls[mt[i]-1] = -1
                            bbb += 1
        it = copy.deepcopy(update)
        for i in update:
            if ls[i] != -1:
                mt[i] = a[i][ls[i]]
        if bbb == n:
            print(cnt, 0)
            exit()
        if not bb:
            print(-1, 0)
            exit()


if __name__ == '__main__':
    slove()