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:
from collections import deque
N = int(input())
A = [deque(list(map(int, input().split()))) for _ in range(N)]
ans = 0
t = 0
for i in range(10**3+1):
    for k in range(N):
        if A[k] != deque([]):
            if A[k][0] == 0:
                A[k].popleft()
        else:
            t += 1
    if t == N:
        break
    t = 0
    for j in range(N):
        if A[j]:
            tmp = A[j][0]
        else:
            continue
        if tmp-1 > j and A[tmp-1][0] -1 == j:
            A[j][0] = 0
            A[tmp-1][0] = 0
    ans += 1
if ans == 1001:
    print(-1)
    exit()
print(ans-1)

Submission status: Wrong Answer

Solution code:
def make_tree(index, a_list):
    depth = 1
    for a in a_list:
        x, y = min(index, a), max(index, a)
        depth = max(tree[x, y], depth)
        tree[x, y] = depth
        depth += 1

import collections

tree = collections.Counter()

N = int(input())
for n in range(N):
    a_list = list(map(int, input().split()))
    make_tree(n + 1, a_list)
    
if(tree.most_common()[-1][1] != 1):
    print(-1)
else:
    print(tree.most_common()[0][1])

Submission status: Wrong Answer

Solution code:
def make_tree(index, a_list):
    depth = 1
    for a in a_list:
        depth = max(tree[min(index, a), max(index, a)], depth)
        tree[min(index, a), max(index, a)] = depth
        depth += 1

import collections

tree = collections.Counter()

N = int(input())
for n in range(N):
    a_list = list(map(int, input().split()))
    make_tree(n + 1, a_list)
    
if(tree.most_common()[-1][1] != 1):
    print(-1)
else:
    print(tree.most_common()[0][1])

Submission status: Wrong Answer

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

empty = [ [] for i in range(N) ]
default = [0 for i in range(N)]
day = 0
while(True):
    day += 1
    v = default
    for p in range(N):
        if (not p in v) or len(A[p]) == 0:
            continue
        q = A[p][0]-1
        if v[p] == 0  and  v[q] == 0  and  A[q][0]-1 == p:
            v[p] = 1
            v[q] = 1
            del A[p][0]
            del A[q][0]
        
    if A == empty:
        print(day)
        break
        
    if v == default:
        print(-1)
        break

Submission status: Wrong Answer

Solution code:
N = int(input())

A = [ [int(i) for i in input().split() ] for j in range(N) ]

for i in range(N):
	A[i].append(-1)
	A[i] = [int(s) for s in A[i]]



# Hはリスト
def search(H):
	list=[]
	counter = 0
	for i in range(N):
		if H.count(i+1) > 0:
			l = H.index(i+1)

			if H[i] == l+1 and l > i:
				list.append((i,l))
				counter += 1

	list.append(counter)
	return list

depth_col = [0]*N

look = []

for _ in range(N):
	look.append(A[_][0])

counter = 0

while min(depth_col) < N-1:
	result = search(look)

	if result[-1] == 0:
		break
	else:
		lengh_search = len(result)-1
		for j in range(lengh_search):
			x = result[j][0]
			y = result[j][1]
			depth_col[x] += 1
			depth_col[y] += 1

			a = depth_col[x]
			b = depth_col[y]
			look[x] = A[x][a]
			look[y] = A[y][b]

		counter += 1


print(counter)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = []
mx = N * (N-1) // 2 + 1
ans = 0
for _ in range(N):
    a = list(map(int, input().split()))
    A.append(a)

for _ in range(mx):
    cnt = 0
    for i in range(N):
        if A[i]:
            pos = A[i][0] - 1
            vs = A[pos][0] - 1
            if  vs == i:
                A[i] = A[i][1::]
                A[pos] = A[pos][1::]
        else:
            cnt += 1
    ans += 1
    if cnt == N:
        break

if ans == mx:
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

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

def league():
    i  = lambda: int(input())
    li = lambda: list(map(int, input().split()))
        
    N = i()
    A = [li() for _ in range(N)]
    
    day = 0
    while True:
        day += 1
        vsp = []
        tp = []
        for i in range(N):
            p = i
            if i in vsp:
                continue
            if len(A[p]) == 0:
                continue
            vp = A[p][0]-1
            while p != A[vp][0]-1:
                tp += [p]
                p = vp
                vp = A[p][0]-1
                if vp in tp:
                    return '-1'
            if vp in vsp or p in vsp:
                continue
            vsp += [p, vp]
            A[p] = A[p][1:]
            A[vp] = A[vp][1:]
        if sum([len(a) for a in A]) == 0:
            return day

print(league())

Submission status: Wrong Answer

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



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

    # print(A)
    # return

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

    # print(outs, ins)
    # return

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

    if not q:
        print(-1)
        return

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


main()

Submission status: Wrong Answer

Solution code:
n = int(input())
ann = [[int(x) for x in input().split()]for i in range(n)]
# print(ann)

indexes = [0 for x in range(n+1)]
#
days = 0
match_count = 0
fight_persons = {}
while(match_count < (n*(n-1))//2):
    fight_persons = set([])
    # print(f"{days} day")
    # print(indexes)
    for self_i,an in enumerate(ann):
        self_i += 1
        # print(f"self_i = {self_i}")
        if self_i in fight_persons or n-1 <= indexes[self_i]:
            continue
        person_i = an[indexes[self_i]]
        # print(f"person_i = {person_i}")
        if ann[person_i-1][indexes[person_i]] == self_i:
            # print("fight!!!")
            # print(person_i,self_i)
            match_count += 1
            indexes[self_i] += 1
            indexes[person_i] += 1
            fight_persons.add(self_i)
            fight_persons.add(person_i)
    # print(fight_persons)
    if len(fight_persons) > 0:
        days += 1
    else:
        break


# print("+++++++++++++++")
if match_count < (n*(n-1))//2:
    print(-1)
else:
    print(days)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [list(map(int, input().split(" "))) for i in range(N)]
count = [0 for i in range(N)]
Ns = [N - 1 for i in range(N)]
days = 0
alert = 0
print(count)

while count != Ns:
    alert = 0
    already = [0 for i in range(N)]
    days = days + 1
    for i in range(N):
        if count[i] == N - 1:
            continue
        for j in range(N):
            if count[j] == N - 1:
                continue
            if count[j] == N - 1:
                continue
            if j == i:
                continue
            if already[i] == 0 and already[j] == 0 and j == A[i][count[i]] - 1 and i == A[j][count[j]] - 1:
                count[i] = count[i] + 1
                count[j] = count[j] + 1
                already[i] = 1
                already[j] = 1
                alert = 1
            print(count)
            print(i, j)
            print(alert)
    if alert == 0:
        print(-1)
        break
    if count == Ns:
        print(days)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# coding=utf-8
import sys

INF = float("inf")


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

    def add_edge(self, edge):
        """辺を加える。edgeは(始点, 終点、重み)からなるリスト
        重みがなければ、重み1とする。
        """
        if len(edge) == 2:
            edge.append(1)
        elif len(edge) != 3:
            print("error in add_edge")
            pass

        s, t, w = edge
        self.E[s].append([t, w])
        pass


def BellmanFord(g: Graph, s):
    """ベルマンフォード法による最短経路
    """
    N = g.N
    dist = [INF] * N
    dist[s] = 0
    prev = [None] * N

    # 辺の緩和
    for _ in range(N):
        for from_ in range(N):  # ここの２重ループはO(M)
            for to_, weight in g.E[from_]:
                if dist[to_] > dist[from_] + weight:
                    dist[to_] = dist[from_] + weight
                    prev[to_] = from_
    # 負の重みの閉路がないかチェック
    for from_ in range(N):
        for to_, weight in g.E[from_]:
            if dist[from_] + weight < dist[to_]:
                return None, None

    return dist, prev


def solve(N: int, A: "List[List[int]]"):
    g = Graph(N * (N - 1) + 2)
    for i in range(N):
        for j in range(N - 1):
            A[i][j] -= 1

    # 重み0
    for i, a in enumerate(A):
        for j, b in enumerate(a):
            s = (N - 1) * i + j
            t = -1
            for k, c in enumerate(A[b]):
                if c == i:
                    t = (N - 1) * b + k
                    break
            g.add_edge([s, t, 0])
            g.add_edge([t, s, 0])

    # 重み1
    for i, a in enumerate(A):
        for j, b in enumerate(a):
            if j < N - 2:
                s = (N - 1) * i + j
                t = (N - 1) * i + j + 1
                g.add_edge([s, t, -1])
            else:
                g.add_edge([s, N * (N - 1), 0])

    for i in range(N):
        t = i * N
        g.add_edge([N * (N - 1) + 1, t, -1])

    dist, prev = BellmanFord(g, N * (N - 1) + 1)

    if dist is None:
        print(-1)
    else:
        print(-1 * min(dist))

    return


# Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [[int(next(tokens)) for _ in range(N - 1)] for _ in range(N)]  # type: "List[List[int]]"
    solve(N, A)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
_match = {}
for i in range(N):
    _match[i + 1] = [int(j) for j in input().split(' ')]

all_match_count = N * (N-1) // 2
match = []
for p, lst in _match.items():
    result = []
    for t in lst:
        if p > t:
            result.append((t, p))
        else:
            result.append((p, t))
    match.append(result)

today_match = set()
already_finish = set()
result = 0
for _ in range(all_match_count):
    could_make_match = False
    for i in range(N):
        try:
            c = match[i][0]
        except IndexError:
            continue
        if c in already_finish:
            match[i].pop(0)
            try:
                c = match[i][0]
            except IndexError:
                continue
        # 試合が見つかった
        if c in today_match:
            today_match.remove(c)
            already_finish.add(c)
            match[i].pop(0)
            could_make_match = True
        else:
            today_match.add(c)
        #print(today_match, already_finish)
    if not could_make_match:
        result = -1
        break
    result += 1
    #print('day' + str(result))
    today_match = set()

print(result)

Submission status: Wrong Answer

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

N = int(input())

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

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


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

print(ans_tmp1)

Submission status: Wrong Answer

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



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

    # print(A)
    # return

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

    # print(outs, ins)
    # return

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

    # q = deque(v1 for v1 in range(1, N+1) if ins[v1] == 0)
    res = []
    depth_max = 0
    while q:
        v1, depth = q.popleft()
        res.append(v1)
        for v2 in outs[v1]:
            ins[v2] -= 1
            if ins[v2] == 0:
                q.append([v2, depth+1])
                depth_max = max(depth_max, depth+1)
    if q or not res:
        print(-1)
        return
    else:
        print(depth_max+1)
        return


main()

Submission status: Wrong Answer

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
A = []
for i in range(N):
    A.append(list(map(int,input().split())))
test = [0]*N
count = [0]*N
# print(test)
M = N*(N-1)//2
day = 0 #日数
for j in range(M):
    for i in range(N):
        if test[i] <= N-2:
            aite = A[i][test[i]]
            if A[aite-1][test[aite-1]] == i+1 and count[aite-1] == 0 and count[i] == 0 :
                test[i]+= 1
                test[aite-1]+=1
                count[i]+=1
                count[aite-1]+=1
    count = [0]*N
    day+=1
    # print(test)
    # print(day)
    if sum(test) == M*2:
        break
    elif sum(test) == 0:
        day = -1
print(day)

Submission status: Wrong Answer

Solution code:
N = int(input())
items = []
from collections import deque

for i in range(N):
    items.append(deque(map(int, input().split())))

ans = 0
from collections import defaultdict

while True:
    used = set()
    flag = False
    for j in range(N):
        if j + 1 in used:
            continue
        if len(items[j]) >= 1:
            t = items[j][0]
            if t not in used and len(items[t - 1]) >= 1 and j + 1 == items[t - 1][0]:
                used.add(j + 1)
                used.add(t)
                items[j].popleft()
                items[t - 1].popleft()
                flag = True
    all_done = True
    for i in range(N):
        if len(items[i]) != 0:
            all_done = False
    if flag:
        ans += 1
    else:
        print(-1)
        exit()
    if all_done:
        break
    if ans >= 10 ** 3 * 2:
        print(N*(N-1)//2)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import collections
sys.setrecursionlimit(4100000)
a = int(input())
b = [collections.deque([int(i) for i in input().split()]) for _ in range(a)]
counter = 0
yesno = True
while True:
    found = False
    done = [False] * len(b)
    for i in range(len(b)):
        if len(b[i]) >= 1:
            target = b[i][0]-1
            if not done[target] and len(b[target]) >= 1:
                if b[target][0] == i+1:
                    b[i].popleft()
                    b[target].popleft()
                    done[i] = True
                    done[target] = True
                    found = True
    if not found:
        break
    counter += 1
for a in b:
    if a != collections.deque([]):
        yesno = False
        break
if not yesno:
    print(-1)
else:
    print(counter)

Submission status: Wrong Answer

Solution code:
# pypy ver. 計算量はせいぜいO(n^2) < 10**6 程度だと想定したのだけれど、そうではないのか？それともほかの理由？
def judge_and_count(A_lst, already_played, played_count):
    count = 0
    roop_count = 0 ##########
    while sum(played_count) < N*(N-1): # 10**3  sumに10**3
        new_play = False
        for i in range(1, N+1): # 10**3
            roop_count += 1 ##########
            if roop_count > 5*10**7: #####
                return -1###########
            if len(A_lst[i]) > 0 and already_played[i] == 0:
                p1 = i
                p2 = A_lst[i][0]
                if len(A_lst[p2]) == 0:
                    return -1
                if already_played[p2] == 1:
                    continue
                if A_lst[p2][0] == p1:
                    already_played[p1] = 1
                    already_played[p2] = 1
                    A_lst[p1].pop(0)
                    A_lst[p2].pop(0)
                    played_count[p1] += 1
                    played_count[p2] += 1
                    new_play = True
        count += 1

        for i in range(len(already_played)): # 10**3
            already_played[i] = 0
        if not new_play:
            return -1
    
    return count


N = int(input())

already_played = [0]*(N+1)
played_count = [0]*(N+1)

A_lst = [[]]


for i in range(N):
    A_low = list(map(int, input().split()))
    A_lst.append(A_low)


ans = judge_and_count(A_lst, already_played, played_count)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = [deque(list(map(int, input().split()))) for _ in range(N)]
ans = 0
t = 0
for i in range(10**3+1):
    print(A)
    for k in range(N):
        if A[k] != deque([]):
            if A[k][0] == 0:
                A[k].popleft()
        else:
            t += 1
    if t == N:
        break
    t = 0
    for j in range(N):
        if A[j]:
            tmp = A[j][0]
        else:
            continue
        if tmp-1 > j and A[tmp-1][0] -1 == j:
            A[j][0] = 0
            A[tmp-1][0] = 0
    ans += 1
if ans == 1001:
    print(-1)
    exit()
print(ans-1)

Submission status: Wrong Answer

Solution code:
# pypy ver. 計算量はせいぜいO(n^2) < 10**6 程度だと想定したのだけれど、そうではないのか？それともほかの理由？
def judge_and_count(A_lst, already_played, played_count):
    count = 0
    roop_count = 0 ##########
    while sum(played_count) < N*(N-1): # 10**3  sumに10**3
        new_play = False
        for i in range(1, N+1): # 10**3
            roop_count += 1 ##########
            if roop_count > 3*10**7: #####
                return -1###########
            if len(A_lst[i]) > 0 and already_played[i] == 0:
                p1 = i
                p2 = A_lst[i][0]
                if len(A_lst[p2]) == 0:
                    return -1
                if already_played[p2] == 1:
                    continue
                if A_lst[p2][0] == p1:
                    already_played[p1] = 1
                    already_played[p2] = 1
                    A_lst[p1].pop(0)
                    A_lst[p2].pop(0)
                    played_count[p1] += 1
                    played_count[p2] += 1
                    new_play = True
        count += 1

        for i in range(len(already_played)): # 10**3
            already_played[i] = 0
        if not new_play:
            return -1
    
    return count


N = int(input())

already_played = [0]*(N+1)
played_count = [0]*(N+1)

A_lst = [[]]


for i in range(N):
    A_low = list(map(int, input().split()))
    A_lst.append(A_low)


ans = judge_and_count(A_lst, already_played, played_count)

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = []
for i in range(N):
	l = list(map(int,input().split()))
	A.append([i-1 for i in l])
match_num = [0 for i in range(N)]
match_dict = {}
idx = 0
for i in range(N-1):
	for j in range(i+1, N):
		match_dict[(i,j)] = idx
		idx += 1
M = idx
edge = [[] for i in range(M)]
parent = [[] for i in range(M)]
for i in range(N):
	for j in range(N-2):
		a = A[i][j]
		a_nxt = A[i][j+1]
		x,y = min(i,a), max(i,a)
		z,w = min(i,a_nxt), max(i,a_nxt)
		m1 = match_dict[(x,y)]
		m2 = match_dict[(z,w)]
		edge[m1].append(m2)
		parent[m2].append(m1)
finish = [False for i in range(M)]
candidate = [(i, 0) for i in range(M) if len(parent[i]) == 0]
depth = [-1 for i in range(M)]
longest = 0
while len(candidate) > 0:
	x = candidate.pop()
	c,d = x[0], x[1]
	if depth[c] <= d:
		continue
	depth[c] = d
	if d > N*(N-1):
		break
	finish[c] = True
	e = None
	for e in edge[c]:
		x,y = min(c,e), max(c,e)
		candidate.append((e, d+1))
	if e == None:
		longest = max(longest, d)
all_finished = all(finish)
if all_finished:
	print(longest + 1)
else:
	print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = [deque(list(map(int, input().split()))) for _ in range(N)]
ans = 0
t = 0
for i in range(10**3+2):
    print(A)
    for k in range(N):
        if A[k] != deque([]):
            if A[k][0] == 0:
                A[k].popleft()
        else:
            t += 1
    if t == N:
        break
    t = 0
    for j in range(N):
        if A[j]:
            tmp = A[j][0]
        else:
            continue
        if tmp-1 > j and A[tmp-1][0] -1 == j:
            A[j][0] = 0
            A[tmp-1][0] = 0
    ans += 1
if ans == 1001:
    print(-1)
    exit()
print(ans-1)

Submission status: Wrong Answer

Solution code:
def main():

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

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

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

    

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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



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

    # print(A)
    # return

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

    # print(outs, ins)
    # return

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

    # q = deque(v1 for v1 in range(1, N+1) if ins[v1] == 0)
    res = []
    depth_max = 0
    while q:
        v1, depth = q.popleft()
        res.append(v1)
        for v2 in outs[v1]:
            ins[v2] -= 1
            if ins[v2] == 0:
                q.append([v2, depth+1])
                depth_max = max(depth_max, depth+1)
    if q or not res:
        print(-1)
        return
    else:
        print(depth_max+1)
        return


main()

Submission status: Wrong Answer

Solution code:
def getT(i, j):
    if (i < j):
        return T[i - 1][j - i - 1]
    else:
        return getT(j, i)


def setT(i, j, value):
    if (i < j):
        T[i - 1][j - i - 1] = value
    else:
        return setT(j, i, value)


def calc(N):
    A = [int(s) for s in input().split()]
    count = 1
    for a in A:
        setT(1, a, count)
        count += 1
    result = 0
    for i in range(2, N):
        A = [int(s) for s in input().split()]
        count = 1
        for a in A:
            b = getT(i, a)
            if (b == 0):
                C = [getT(a, j) for j in range(1, i) if a != j]
                C.sort()
                for c in C:
                    if (count != c):
                        break
                    count += 1
                setT(i, a, count)
            else:
                count = b + 1
        result = max(result, count)
    A = [int(s) for s in input().split()]
    B = [getT(a, N) for a in A]
    for i in range(N - 2):
        if (B[i] > B[i + 1]):
            return - 1
    return result


N = int(input())
T = [
    [0 for _ in range(N - i - 1)]
    for i in range(N - 1)
]
print(calc(N))