Problem:


Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

1 \leq A_{i, j} \leq N

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

4
2 3 4
1 3 4
4 1 2
3 1 2

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.



Sample input:
3
2 3
1 3
1 2


Sample output:
3

Submission status: Runtime Error

Solution code:
import collections as cl
mod = 10**9+7

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

def Topo_sort(x,y):
    co = cl.Counter(n for m in x.values() for n in m)
    S = cl.deque([i for i in range(y) if co[i] == 0])
    while S:
        n = S.popleft()
        yield n
        for i in x[n]:
            co[i] -= 1
            if co[i] <= 0:
                S.append(i)
    ```
    if sum(co.values()) != 0:
        print(1)
        exit()
    else:
        print(0)
        exit()
    ```
    #閉路検出(1が存在,0が存在しない)
# g = cl.dafaultdict(set)に有向グラフを作成し(g[~] != ~ ,yはノード数) リストが帰ってくる

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline

n = int(input())
N =n*(n-1)//2

"""
a = [[min(i,int(j)-1)+max(i,int(j)-1)*(max(i,int(j)-1)-1)//2 for j in readline().split()] for i in range(n)]
g = [[] for i in range(N)]
p = [[] for i in range(N)]
for i in range(n):
    for j in range(n-2):
        g[a[i][j]].append(a[i][j+1])
        p[a[i][j+1]].append(a[i][j])
"""

a = [[int(j)-1 for j in readline().split()] for i in range(n)]

g = {(i,j): [] for i in range(n) for j in range(i+1,n)}
p = {(i,j): [] for i in range(n) for j in range(i+1,n)}
for i in range(n):
    for j in range(n-2):
        if i < a[i][j]:
            ij = (i, a[i][j])
        else:
            ij = (a[i][j],i)
        if i < a[i][j+1]:
            ijj = (i, a[i][j+1])
        else:
            ijj = (a[i][j+1],i)
        g[ij].append(ijj)
        p[ijj].append(ij)

print(g)

"""
トポロジカルソート
DAG なら
g: グラフの隣接行列
p: 逆辺の隣接行列

q をheapq にしたりすると、辞書順にとりだしたりとかができる。
"""
def topological_sort_queue(g,p):
#    indegree = [len(v) for v in p] # 流入辺の数を数えた配列
#    q = [i for i, c in enumerate(indegree) if c == 0] #流入辺0の点の集合
    indegree = {v:len(vc) for v,vc in p.items()} # 流入辺の数を数えた配列
    q = [i for i, c in indegree.items() if c == 0] #流入辺0の点の集合
    L = [] #ソート結果をためておく配列

    ans = {i:0 for i in g}
    a = 0
    print(p)
    print(indegree)
    print(q)
    while q:
        v = q.pop()
        L.append(v)
        for c in g[v]: #配る
            ans[c] = max(ans[c],ans[v]+1)
            a = max(a,ans[c])
            indegree[c] -= 1 #辺 node -> child を削除する
            if indegree[c] == 0:
                q.append(c)
    if len(L) != N:
#        print("サイクル検出")
        return -1
    else:
#        return(L)
        return(a+1)        

print(topological_sort_queue(g,p))

assert n!=3

Submission status: Runtime Error

Solution code:
from collections import deque

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

memo=[1 for i in range(N)]
ans=[]
    
def d(i,loop):
    if len(A[i])>0:
        j=A[i][0]-1
        if i==A[j][0]-1:
            A[i].popleft()
            A[j].popleft()
            if memo[i]==1:
                ans.append(1)
                memo[i]-=1
            else:
                memo[i]+=1
            if memo[j]==1:

                memo[j]-=1
            else:
                memo[j]+=1
            return
        
        else:
            if loop<=N:
                loop+=1
                return d(j,loop)
            else:
                return
    
    elif loop==N-1:
        return 
    else:
        loop+=1
        return d(i+1,loop)

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

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

Submission status: Runtime Error

Solution code:
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):
        for j in range(N):
            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: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using P = pair<ll, ll>;
using edge = pair<ll, P>;
#define rep(i, n) for(ll i=0;i<(ll)(n);i++)
#define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++)
#define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--)
using Graph = vector<vector<ll>>;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll MOD = 1000000007;
const ll INF = 1000000000000000000L;
#ifdef __DEBUG

#include "cpp-pyprint/pyprint.h"

#endif

void Main() {
    int N;
    cin >> N;
    vector<deque<ll>> items(N);
    rep(i, N) {
        rep(j, N - 1) {
            int a;
            scanf("%d", &a);
            items[i].push_back(a);
        }
    }

    ll ans = 0;

    while (ans < (ll)(N)*(N-1)/2+2) {
        unordered_set<ll> used;
        bool flag = false;
        bool all_done = true;
        int cnt = 0;
        int tt = 0;
        rep(j, N) {
            if (used.find(j + 1) != used.end()) {
                continue;
            }
            if (items[j].size() >= 1) {
                ll t = items[j][0];
                if (used.find(t) == used.end() && items[t - 1].size() >= 1 && j + 1 == items[t - 1][0]) {
                    used.insert(j + 1);
                    used.insert(t);
                    items[j].pop_front();
                    items[t - 1].pop_front();
                    flag = true;
                    cnt ++;
                }
            }
            if (items[j].size() != 0){
                all_done = false;
            }
        }
        if (cnt==1){
            tt++;
            if(tt >= 100){
                cout << (N)*(N+1)/2 << endl;
                return;
            }
        }
        if (ans > (N/10) * N){
            cout << (N+1)*N/2 << endl;
            return;
        }
        if (flag) {
            ans++;
        }else{
            cout << -1 << endl;
            return;
        }
        if(ans > (ll)(N)*(N-1)/2){
            cout << -1 << endl;
            break;
        }
        if (all_done) {
            cout << ans << endl;
            break;
        }
      	if ans >= 10**4:
      		print(N*(N-1)//2)
      		exit()

    }

}

int main() {
    Main();
}

Submission status: Runtime Error

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

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(List[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: Runtime Error

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(List[i])
            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: Runtime Error

Solution code:

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

Submission status: Runtime Error

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):
        for j in range(N):
            if count[j] == N - 1:
                continue
            if j == i:
                continue
            if already[i] == 0 and already[j] == 0 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
    if count == Ns:
        print(days)
    if alert == 0:
        print(-1)
        break

Submission status: Runtime Error

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

n = onem()

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


co = 1
ddd = cl.deque()
de.append([-1,-1])
cl = [1 for i in range(n)]

while de:

    kkk = de.popleft()
    if kkk[0] == -1 and kkk[1] == -1:
        if sum(cl) == n:
            co = -1
            break
        if len(de) == 0:
            break
        de.append([-1,-1])
        co += 1
        cl = [1 for i in range(n)]

    elif on[kkk[0]][0] == kkk[1] and cl[kkk[0]] and cl[kkk[1]]:
        cl[kkk[0]] = 0
        cl[kkk[1]] = 0
        on[kkk[0]].popleft()
        on[kkk[1]].popleft()
        if len(on[kkk[1]]) != 0 and len(on[kkk[0]]) != 0 and on[kkk[1]][0] == kkk[0] and on[kkk[0]][0] == kkk[1]:
            de.append([on[kkk[1]][0],kkk[1]])
        else:
            if len(on[kkk[1]]) != 0:
                de.append([on[kkk[1]][0],kkk[1]])
            if len(on[kkk[0]]) != 0:
                de.append([on[kkk[0]][0],kkk[0]])


print(co)

Submission status: Runtime Error

Solution code:
import sys, time
def input():
	return sys.stdin.readline()[:-1]

n = int(input())
a = [list(map(int, input().split()))[::-1] for _ in range(n)]
#print(*a, sep="\n")
opponent = [-1 for _ in range(n)]
played = list(range(n))
match = 0
day = 0
while match < n*(n-1)//2:
	approved = False
	for i in played:
		if a[i] != []:
			opponent[i] = a[i].pop()-1
	played = []
	#print(opponent)
	for i in range(n):
		if opponent[i] != -1 and opponent[opponent[i]] == i:
			approved = True
			match += 1
			played.append(i, opponent[i])
			opponent[opponent[i]] = -1
			opponent[i] = -1
	#print(opponent)
	if not approved:
		print(-1)
		sys.exit()
	day += 1
print(day)

Submission status: Runtime Error

Solution code:
*D, = open(0)
n = int(D[0])
data = []
for i in range(n):
    l = map(int, D[i+1].split())
    data.append([val-1 for val in l])
    
    
from collections import deque
table = []
for i in range(n):
    table.append(deque())
    for j in data[i]:
        if i > j:
            table[i].append('{},{}'.format(j,i))
        else:
            table[i].append('{},{}'.format(i,j))
        
        
cnt = 0
while True:
    candi = {}
    END = True
    del_idx = []
    for i, que in enumerate(table):
        if que:
            if que[0] in candi:
                table[i].popleft()
                table[candi[que[0]]].popleft()
                END = False
            else:
                candi[que[0]] = i

    if END:
#         print('end')
        break
    cnt += 1
    
INVALID = True
for it in table:
    if not it:
        INVALID = False
        break

if INVALID:
    print('-1')
else:
    print(cnt)

Submission status: Runtime Error

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

n = onem()

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


co = 1
ddd = cl.deque()
de.append([-1,-1])
cl = [1 for i in range(n)]

while de:

    kkk = de.popleft()
    if kkk[0] == -1 and kkk[1] == -1:
        if sum(cl) == n:
            co = -1
            break
        if len(de) == 0:
            break
        de.append([-1,-1])
        co += 1
        cl = [1 for i in range(n)]

    elif on[kkk[0]][0] == kkk[1] and cl[kkk[0]] and cl[kkk[1]]:
        cl[kkk[0]] = 0
        cl[kkk[1]] = 0
        on[kkk[0]].popleft()
        on[kkk[1]].popleft()
        if on[kkk[1]][0] == kkk[0] and on[kkk[0]][0] == kkk[1]:
            de.append([on[kkk[1]][0],kkk[1]])
        elif len(on[kkk[1]]) != 0:
            de.append([on[kkk[1]][0],kkk[1]])
        elif len(on[kkk[0]]) != 0:
            de.append([on[kkk[0]][0],kkk[0]])


print(co)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
league = []
match = {}
ll = []
for i in range(n):
    league.append(list(map(int, input().split())))
    match[i+1] = league[i][-1]
    ll.append(n-3)
ans = 0
cnt = 0
tmp = [0]
while cnt < n and tmp:
    tmp = []
    for k,v in match.items():
        if match[v] == k:
            tmp.append(v)
    for i in tmp:
        if ll[i-1] < 0:
            cnt += 1
            match[i] = 0
        else:
            match[i] = league[i-1][ll[i-1]]
            ll[i-1] -= 1
    ans += 1
print(ans if n == cnt else -1)

Submission status: Runtime Error

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

n = onem()

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


co = 1
ddd = cl.deque()
de.append([-1,-1])
cl = [1 for i in range(n)]

while de:

    kkk = de.popleft()
    if kkk[0] == -1 and kkk[1] == -1:
        if sum(cl) == n:
            co = -1
            break
        if len(de) == 0:
            break
        de.append([-1,-1])
        co += 1
        cl = [1 for i in range(n)]

    elif on[kkk[0]][0] == kkk[1] and cl[kkk[0]] and cl[kkk[1]]:
        cl[kkk[0]] = 0
        cl[kkk[1]] = 0
        on[kkk[0]].popleft()
        on[kkk[1]].popleft()
        if len(on[kkk[1]]) != 0:
            de.append([on[kkk[1]][0],kkk[1]])
        if len(on[kkk[0]]) != 0:
            de.append([on[kkk[0]][0],kkk[0]])


print(co)

Submission status: Runtime Error

Solution code:
from sys import stdin
import math
import collections
import heapq


class G:
    def __init__(self):
        self.day = collections.defaultdict(int)
        self.next = collections.defaultdict(list)
        self.prev = collections.defaultdict(list)
        self.root = []
        self.solved = collections.defaultdict(bool)
        self.ans = 0
        self.max = -1

    def setmax(self, n):
        self.max = n

    def add(self, u, v, d):
        self.next[u].append(v)
        self.prev[v].append(u)

    def print(self, u):
        print("solved", self.solved[u])
        print("day", self.day[u])
        print("next", self.next[u])
        print("prev", self.prev[u])

    def solve(self, u):
        if self.solved[u]:
            return True
        self.solved[u] = True
        if self.day[u] == 0:
            if len(self.prev[u]) == 0:
                self.day[u] = 1
                self.root.append(u)
                #print("root",u)
            else:
                for i in range(len(self.prev[u])):
                    ret = self.solve(self.prev[u][i])
                for i in range(len(self.next[u])):
                    ret = self.solve(self.next[u][i])
        return False

    def decide(self, u, d):
        if self.ans < 0:
            return
        if self.max < d:
            self.ans = -1
            return
        if self.day[u] <= d:
            self.day[u] = d+1
            self.ans = max(self.ans, self.day[u])

        for i in range(len(self.next[u])):
            self.decide(self.next[u][i], self.day[u])
        return


g = G()

n = int(stdin.readline().rstrip())

g.setmax(n*(n-1)//2)

for i in range(n):
  an = list(map(int, input().split()))
  for j in range(len(an)-1):
      g.add(str({i+1,an[j]}),str({i+1,an[j+1]}),1)

ret = g.solve(str({1,2}))

# print(g.root)

for i in range(len(g.root)):
    g.decide(g.root[i], 0)

if (g.ans == 0):
    g.ans = -1

print(g.ans)

Submission status: Runtime Error

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 not j in schedule:
                    schedule[j] = n-1
                if schedule[j] < ord_j - 1:
                    print(-1)
                    return
                schedule[j] = ord_j - 1
                cand.append([j, ord_j - 1])
                continue
            else:
                day = max([owata[j][ord_j - 1] + 1, day])
                flag = True
        else:
            flag = True
        if flag:
            finished += 1
            day = max([day, ])
            owata[i][ord_i] = day
            owata[j][ord_j] = day
            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:
                for i in range(n):
                    if not already_done[i] == n-2:
                        ord_i = already_done[i] + 1
                        cand.append([i, ord_i])
                        schedule = {i:ord_i}
                        day = 1 if ord_i == 0 else owata[i][ord_i - 1] + 1
                        break
    print(max_day)
    return


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

count = 0
z = True
while l !=[]:
    kyou = [i + 1 for i in range(n)]
    for i in range(n-1):
        if i+1 in kyou:
            number = l[i][0]
            if l[number-1][0] == i+1:
                l[number-1].pop(0)
                l[i].pop(0)
                kyou.remove(number)
                kyou.remove(i+1)
            else:
                z =False
                break
        else:
            pass
    count +=1
if z == False:
    print('-1')
else:
    print(count)

Submission status: Runtime Error

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

count = 0
z = True
while l !=[]:
    kyou = [i + 1 for i in range(n)]
    for i in range(n-1):
        if i+1 in kyou:
            number = l[i][0]
            if l[number-1][0] == i+1:
                l[number-1].pop(0)
                l[i].pop(0)
                kyou.remove(number)
                kyou.remove(i+1)
            else:
                z =False
                break
        else:
            pass
    count +=1

Submission status: Runtime Error

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

n = onem()

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


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

print(co)

Submission status: Runtime Error

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 not j in schedule:
                    schedule[j] = n-1
                if schedule[j] < ord_j - 1:
                    print(-1)
                    return
                schedule[j] = ord_j - 1
                cand.append([j, ord_j - 1])
                continue
            else:
                day = max([owata[j][ord_j - 1] + 1, day])
                flag = True
        else:
            flag = True
        if flag:
            finished += 1
            day = max([day, ])
            owata[i][ord_i] = day
            owata[j][ord_j] = day
            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:
                for i in range(n):
                    if not already_done[i] == n-1:
                        ord_i = already_done[i] + 1
                        cand.append([i, ord_i])
                        schedule = {i:ord_i}
                        day = 1 if ord_i == 0 else owata[i][ord_i - 1] + 1
                        break
    print(max_day)
    return


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

for k in range(30000):
    today = set()
    flag = 0
    for j in range(N):
        if j+1 in today:
            continue
        if index[j+1] >= N-1:
            continue
        #print(j, index[j+1])
        opponent = A[j][index[j+1]]
        if A[opponent-1][index[opponent]] == j+1:
            if opponent not in today:
                index[opponent] += 1
                index[j+1] += 1
                today.add(opponent)
                today.add(j+1)
                flag = 1
    if flag == 0:
        if sum(index) == N*(N-1):
            ans = k
            break
        else:
            ans = -1
            break
    #print(index)

print(ans)