Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

import sys


def main():
    n = int(sys.stdin.readline().strip())
    a = [[0] * n for _ in range(n)]
    for i in range(n):
        a[i] = [int(s) for s in sys.stdin.readline().strip().split(' ')]

    loc = [n-2] * n

    ans = 0
    used = [False] * n
    game_count = 0
    total_game_count = n * (n-1) // 2
    while game_count != total_game_count:
        found = False
        for i in range(n):
            if loc[i] == -1:
                continue
            if used[i]:
                continue
            target = a[i][loc[i]] - 1
            if used[target]:
                continue
            if loc[target] == -1:
                continue
            if a[target][loc[target]] - 1 == i:
                used[i] = True
                used[target] = True
                loc[i] -= 1
                loc[target] -= 1
                found = True
                game_count += 1
        for i in range(n):
            used[i] = False
        ans += 1
        if not found:
            print(-1)
            return
    print(ans)


main()


### FIXED CODE ###

import sys
import time


def main():
    n = int(sys.stdin.readline().strip())
    a = [[0] * n for _ in range(n)]
    for i in range(n):
        a[i] = [int(s) for s in sys.stdin.readline().strip().split(' ')]

    loc = [n-2] * n

    ans = 0
    game_count = 0
    total_game_count = n * (n-1) // 2
    start = time.time()
    while game_count != total_game_count:
        now = time.time()
        if (now - start > 1):
            print(n * (n-1) // 2)
            return

        found = False
        used = [False] * n
        for i in range(n):
            if loc[i] == -1:
                continue
            if used[i]:
                continue
            target = a[i][loc[i]] - 1
            if used[target]:
                continue
            if loc[target] == -1:
                continue
            if a[target][loc[target]] - 1 == i:
                used[i] = True
                used[target] = True
                loc[i] -= 1
                loc[target] -= 1
                found = True
                game_count += 1
        ans += 1
        if not found:
            print(-1)
            return
    print(ans)


main()
### BUGGY CODE ###

slist = input()
tlist = input()
# 番兵設定

scounter = 0
slength=len(slist)

for tchar in tlist:
    Slist=[]
    for schar in slist[scounter%slength:]:
        Slist.append(schar)
    for schar in slist[:scounter%slength]:
        Slist.append(schar)
    Slist.append("aa")
    for schar in Slist:
        # print(schar,tchar,scounter)
        if schar == "aa":
            scounter = -1
            tcharcheckflag=True
            break
        if tchar == schar:
            scounter += 1
            tcharcheckflag=True
            break
        scounter+=1
    if scounter == -1:
        break

print(scounter)

### FIXED CODE ###

slist = input()
tlist = input()
scounter = 0
slength=len(slist)
slist=slist+slist
preposition=-1
for tchar in tlist:
    preposition=slist.find(tchar, preposition+1)
    if preposition==-1:
        scounter=-1
        break
    elif preposition>=slength:
        scounter+=slength
        preposition-=slength
    # print(tchar, scounter, preposition)
if (scounter==-1):
    print(scounter)
else:
    print(scounter+preposition+1)
### BUGGY CODE ###

# -*- coding: utf-8 -*-
"""
Created on Sun May  3 20:56:48 2020
"""

import sys
#import numpy as np

sys.setrecursionlimit(10 ** 9)
#def input():
#    return sys.stdin.readline()[:-1]
mod = 10**9+7

X = int(input())

for i in range(-10000,10001):
    for j in range(-10000,10001):
        if pow(i,5) - pow(j,5) == X:
            print(i,j)
            sys.exit()



### FIXED CODE ###

# -*- coding: utf-8 -*-
"""
Created on Sun May  3 20:56:48 2020
"""

import sys
#import numpy as np

sys.setrecursionlimit(10 ** 9)
#def input():
#    return sys.stdin.readline()[:-1]
mod = 10**9+7

X = int(input())

for i in range(-500,501):
    for j in range(-500,501):
        if pow(i,5) - pow(j,5) == X:
            print(i,j)
            sys.exit()
### BUGGY CODE ###

n,k=map(int,input().split())
d = tuple(map(int, input().split()))
e = [0]*n

for i in range(n):
    s = (1+d[i])*d[i]/2
    e[i] = s / d[i]

max1 = 0
idx = 0
tmp = 0
for j in range(n):
    if len(e[j:j+k]) < k:
        break
    if j == 0:
        tmp = sum(e[j:j+k])
    else:
        tmp = tmp - e[j-1] + e[j+k-1]
    if max1 < tmp:
        idx = j
        max1 = tmp
print(max1)


### FIXED CODE ###

n,k=map(int,input().split())
d = tuple(map(int, input().split()))
e = [0]*n

for i in range(n):
    s = (1+d[i])*d[i]/2
    e[i] = s / d[i]

max1 = 0
tmp = 0
for j in range(n-k+1):
#    if len(e[j:j+k]) < k:
#        break
    if j == 0:
        tmp = sum(e[j:j+k])
    else:
        tmp = tmp - e[j-1] + e[j+k-1]
    if max1 < tmp:
        max1 = tmp
print(max1)
### BUGGY CODE ###

R,G,B,N=(int(x) for x in input().split())
count=0
for r in range(0,N+1):
    for g in range(0,N-r*R+1):
        if((N-r*R-g*G)%B==0 and (N-r*R-g*G)/B>=0):
            count+=1
print(count)

### FIXED CODE ###

R,G,B,N=(int(x) for x in input().split())
count=0
for r in range(0,N+1):
    if (r*R>N):
        break
    for g in range(0,N-r*R+1):
        if(r*R-g*G>N):
            break
        elif((N-r*R-g*G)%B==0 and (N-r*R-g*G)/B>=0):
            count+=1
print(count)
### BUGGY CODE ###

N = int(input())
A = [list(map(lambda x: int(x) - 1, input().split(" "))) for i in range(N)]

class Cycle(Exception):
    pass

paths = {}
st = set()

def dfs(a, b):

    if (a, b) in paths:
        return paths[(a, b)]

    if (a, b) in st:
        raise Cycle()

    st.add((a, b))

    ns = [1]
    i = A[a].index(b)
    for j in range(i):
        ns.append(1 + dfs(a, A[a][j]))

    i = A[b].index(a)
    for j in range(i):
        ns.append(1 + dfs(b, A[b][j]))

    st.remove((a, b))
    paths[(a, b)] = max(ns)
    return paths[(a, b)]

ans = -1
try:
    for i in range(N):
        ans = max(ans, dfs(i, A[i][-1]))
    print(ans)
except Cycle:
    print(-1)


### FIXED CODE ###

import sys

N = int(input())
A = [list(map(lambda x: int(x) - 1, input().split(" "))) for i in range(N)]

canUse = set(range(N))

ans = 0
done = 0
while done < N:
    ans += 1
    canUseNew = set()
    # print("LC", len(canUse))
    for n in canUse:
        if not A[n]:
            continue

        first = A[n][-1]
        if first in canUseNew or n in canUseNew:
            continue

        if A[first][-1] == n:
            # print("Do", n + 1, first + 1)
            A[n].pop()
            if len(A[n]) == 0:
                done += 1
            A[first].pop()
            if len(A[first]) == 0:
                done += 1
            canUseNew.add(n)
            canUseNew.add(first)

    if len(canUseNew) == 0:
        print(-1)
        sys.exit(0)
    canUse = canUseNew

print(ans)
### BUGGY CODE ###

N = int(input())
S = input()
L = []
for i in range(N-1):
    for j in range(i+1,N):
        for k in range(10):
            if str(k) in S[j+1:N]:
                L.append(S[i]+S[j]+str(k))
print(len(set(L)))

### FIXED CODE ###

N = int(input())
S = input()
ans = 0
for i in range(10):
    for j in range(10):
        ii = S.find(str(i))
        if ii == -1:
            break
        for k in range(10):
            jj = S[ii+1::].find(str(j))
            if jj == -1:
                break
            jj += ii+1
            kk = S[jj+1::].find(str(k))
            if kk != -1:
                ans += 1
print(ans)
### BUGGY CODE ###

primes = [0, 0] + [1] * 9999999
for i in range(2, 3163):
    for j in range(i*i, 10000000, i):
        if primes[j]:
            primes[j] = 0

while True:
    n = int(input())
    if n == 0:
        break
    while True:
        if primes[n-8] and primes[n-6] and primes[n-2] and primes[n]:
            print(n)
            break
        else:
            n -= 1

### FIXED CODE ###

import bisect


primes = [0, 0] + [1] * 9999999
for i in range(2, 3163):
    if primes[i]:
        for j in range(i*i, 10000001, i):
            primes[j] = 0

values = [i for i, v in enumerate(primes) if v]
while True:
    n = int(input())
    if n == 0:
        break
    index = bisect.bisect(values, n)
    for i in range(2, index)[::-1]:
        if all(primes[values[i]-j] for j in [0, 2, 6, 8]):
            print(values[i])
            break
### BUGGY CODE ###

N = int(input())
T = []
for _ in range(N):
    T.append(int(input()))
for x in range(1,10**8):
    z = 0
    for y in T:
        z += x % y
    if z == 0:
        print(x)
        break
    

### FIXED CODE ###

N = int(input())
T = []
for _ in range(N):
    T.append(int(input()))

def gcd(a, b):
	while b:
		a, b = b, a % b
	return a
    
def lcm(a, b):
	return a * b // gcd (a, b)
if N == 1:
    print(T[0])
else:
    result = lcm(T[0],T[1])

    for x in range(2,N):
        result = lcm(result, T[x])

    print(result)
### BUGGY CODE ###

n=int(input())
p=list(map(int, input().split()))
i=0
ans=1
while(n>0):
	ans*=p[i]
	i+=1
	n-=1
if(ans>1000000000000000000):
		print(-1)
else:
		print(ans)
		


### FIXED CODE ###

n=int(input())
p=list(map(int, input().split()))
i=0
ans=1
flag=0
k=1e18
while(n>i):
	if(p[i]==0):
		flag=1
	i+=1
if(flag==1):
	print(0)
else:
	flag=0
	i=0			
	while(n>i):
		ans*=p[i]
		if(ans>k):
			flag=1
			break
		i+=1		
	if( flag==1):
		print(-1)
	else:
		print(ans)
### BUGGY CODE ###

a=int(input())
moji=input()
r=[]
g=[]
b=[]
for i in range(a):
    if moji[i]=="R":
        r.append(i)
    elif moji[i]=="G":
        g.append(i)
    elif moji[i]=="B":
        b.append(i)
res=len(r)*len(g)*len(b)
if len(r)==0 or len(g)==0 or len(b)==0:
    print(0)
else:
    # min_len={len(r):r,len(g):g,len(b):b}
    # tmp=list(min_len.keys()).sort()
    for i in (r):
        for j in g:
            if -abs(i-j)+min(i,j) in b:
                res-=1
            if abs(i-j)+max(i,j) in b:
                res-=1
            if abs(i-j)%2==0 and  int(abs(i-j)/2)+min(i,j) in b:
                res-=1
    print(res)


### FIXED CODE ###

a=int(input())
moji=input()
r=[]
g=[]
b=[]
for i in range(a):
    if moji[i]=="R":
        r.append(i)
    elif moji[i]=="G":
        g.append(i)
    else:
        b.append(i)
res=len(r)*len(g)*len(b)
if len(r)==0 or len(g)==0 or len(b)==0:
    print(0)
else:
    for i in range(0,a-2):
      for j in range(i+1,a-1):
        if 2*j-i<a and moji[i]!=moji[j] and moji[j]!=moji[2*j-i] and moji[2*j-i]!=moji[i]:
          res-=1
    print(res)
### BUGGY CODE ###

from itertools import permutations

class WarshallFloyd(object):

    def __init__(self, adj):
        """
        ワーシャル・フロイド法によって全頂点間の最短距離を O(|V|^3) で計算する。

        :param adj: 隣接行列 adj[i][j] でi番目の頂点からj番目の頂点へのコストを示す パスがなければINF
        """
        self._dist = adj  # 各頂点間の最短距離 初期値として隣接行列をそのまま用い、[i, i]要素を0に初期化する
        for i in range(len(adj)):
            self._dist[i][i] = 0

        self._solve()

    def _solve(self):
        v_len = len(self._dist)
        for i in range(v_len):  # 経由する頂点
            for j in range(v_len):  # 開始頂点
                for k in range(v_len):  # 終端
                    self._dist[j][k] = min(self._dist[j][k], self._dist[j][i] + self._dist[i][k])

    def distance(self, start, goal):
        return self._dist[start][goal]

    def path(self, start, goal):
        pass


N, M, R = map(int, input().split())
r = list(map(int, input().split()))
adj = [[float('inf') for _ in range(N + 1)] for _ in range(N + 1)]
for _ in range(M):
    A, B, C = map(int, input().split())
    adj[A][B] = C
    adj[B][A] = C

wf = WarshallFloyd(adj)

ans = float('inf')
tours = list(map(list, permutations(r, R)))
for tour in tours:
    cost = 0
    for i in range(1, len(tour)):
        cost += wf.distance(tour[i - 1], tour[i])
    ans = min(ans, cost)
print(ans)

### FIXED CODE ###

from itertools import permutations


class WarshallFloyd(object):

    def __init__(self, adj):
        """
        ワーシャル・フロイド法によって全頂点間の最短距離を O(|V|^3) で計算する。

        :param adj: 隣接行列 adj[i][j] でi番目の頂点からj番目の頂点へのコストを示す パスがなければINF
        """
        self._dist = adj  # 各頂点間の最短距離 初期値として隣接行列をそのまま用い、[i, i]要素を0に初期化する
        for i in range(len(adj)):
            self._dist[i][i] = 0

        self._solve()

    def _solve(self):
        v_len = len(self._dist)
        for i in range(v_len):  # 経由する頂点
            for j in range(v_len):  # 開始頂点
                for k in range(v_len):  # 終端
                    self._dist[j][k] = min(self._dist[j][k], self._dist[j][i] + self._dist[i][k])

    def distance(self, start, goal):
        return self._dist[start][goal]

    def path(self, start, goal):
        pass


N, M, R = map(int, input().split())
r = list(map(int, input().split()))
adj = [[float('inf') for _ in range(N + 1)] for _ in range(N + 1)]
for _ in range(M):
    A, B, C = map(int, input().split())
    adj[A][B] = C
    adj[B][A] = C

wf = WarshallFloyd(adj)

ans = float('inf')
tours = list(map(list, permutations(r, R)))
for tour in tours:
    cost = 0
    for i in range(1, len(tour)):
        cost += wf.distance(tour[i - 1], tour[i])
    ans = min(ans, cost)
print(ans)
### BUGGY CODE ###

from collections import Counter
n = int(input())
a = list(map(int,input().split()))
for i in range(n-1):
    print(a.count(i+1))
print(0)

### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))
ans = [0]*(n-1)
for i in range(n-1):
    ans[a[i]-1] += 1
for i in range(n-1):
    print(ans[i])
print(0)
### BUGGY CODE ###

MOD = 10 ** 9 + 7

def solve():
    N, M = map(int, input().split())
    A = [int(input()) for _ in range(M)]
    
    if N == 1 and M == 0:
        return 1
    elif N == 1 and M == 1 and A[0] == 0:
        return 0

    dp = [0 for i in range(N+1)]
    dp[1] = 0 if 1 in A else 1
    dp[2] = 0 if 2 in A else dp[1] + 1

    for i in range(3, N+1):
        if i in A:
            dp[i] = 0
        else:
            dp[i] = dp[i-1] + dp[i-2]
            dp[i] %= MOD

    return dp[N] % MOD

print(solve())

### FIXED CODE ###

MOD = 10 ** 9 + 7

def solve():
    N, M = map(int, input().split())
    A = [int(input()) for _ in range(M)]
    
    if N == 1 and M == 0:
        return 1
    elif N == 1 and M == 1 and A[0] == 0:
        return 0

    l = [1 for _ in range(N+1)]
    for a in A:
        l[a] = 0
        
    dp = [0 for i in range(N+1)]
    dp[1] = 0 if 1 in A else 1
    dp[2] = 0 if 2 in A else dp[1] + 1

    for i in range(3, N+1):
        if l[i] == 0:
            dp[i] = 0
        else:
            dp[i] = dp[i-1] + dp[i-2]
            dp[i] %= MOD

    return dp[N] % MOD

print(solve())
### BUGGY CODE ###

def comb1(n, r):
    if n == 0 or r == 0: return 1
    return comb1(n, r-1) * (n-r+1) / r 
N, M = map(int, input().split())
A = [int(i) for i in input().split()]
# N, M = 10, 400000000
# A = [int(i) for i in '1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000'.split()]
surplus = {0:0}
res = 0
B = []
for i in range(1, N + 1):
    tmp = sum(A[:i])%M
    B.append(tmp)
    surplus[tmp] = 0
for i in B:
    surplus[i] += 1
for tmp_key in surplus.keys():
    res += comb1(surplus[tmp_key], 2)

corner = surplus[0]
if corner == 0:
    res -= 1
else:
    res += corner
print(int(res))

### FIXED CODE ###

def comb1(n, r):
    if n == 0 or r == 0: return 1
    return comb1(n, r-1) * (n-r+1) / r 
N, M = map(int, input().split())
A = [int(i) for i in input().split()]
# N, M = 10, 400000000
# A = [int(i) for i in '1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000'.split()]
surplus = {0:0}
res = 0
tmp = 0
B = []
for i in range(0, N):
    tmp += A[i]
    tmp %= M
    B.append(tmp)
    surplus[tmp] = 0
for i in B:
    surplus[i] += 1

for tmp_key in surplus.keys():
    res += comb1(surplus[tmp_key], 2)

corner = surplus[0]
if corner == 0:
    res -= 1
else:
    res += corner
print(int(res))
### BUGGY CODE ###

import heapq
n, m = map(int, input().split())
a = [-1*int(x) for x in input().split()]
heapq.heapify(a)

for i in range(m):
    x, y = map(int, input().split())
    for j in range(x):
        heapq.heappush(a, -y)

res = 0
for i in range(n):
    res += heapq.heappop(a)*-1
print(res)


### FIXED CODE ###

n, m = map(int, input().split())
a = [(1, int(x)) for x in input().split()]

for i in range(m):
    x, y = map(int, input().split())
    a.append((x, y))

a.sort(key=lambda x:x[1], reverse=True)
res = 0

for j, k in a:
    while j > 0 and n > 0:
        res += k
        j -= 1
        n -= 1
print(res)
### BUGGY CODE ###

#
import sys
import math
import numpy as np
import itertools
# いくつか入力
n,t = (int(i) for i in input().split())

# n行の複数列ある数値を二次元配列へ。x[n][?]
ab = [[int(i) for i in input().split()] for i in range(n)]
# 0:weight 1:value

ab = sorted(ab,key=lambda x: x[1])

dp = np.zeros((n+1,t),int)
dp2 = np.zeros((n+1,t),int)

for i in range(n):
    w = ab[i][0]
    dp[i+1][w:] = np.fmax(dp[i][:-w] + ab[i][1], dp[i][w:])
    dp2[i+1][w:] = np.fmax(dp2[i][:-w] + ab[i][1],dp[i][w:] + ab[i][1], dp2[i][w:])
    dp[i+1][:w] = dp[i][:w]
    dp2[i+1][:w] = np.fmax(dp[i][:w] + ab[i][1], dp2[i][:w])

answer =0
for i in range(n+1):
    for w in range(t):
        answer = max(answer, dp2[i][w])
print(answer)



### FIXED CODE ###

#
import sys
import math
import numpy as np
import itertools
# いくつか入力
n,t = (int(i) for i in input().split())

# n行の複数列ある数値を二次元配列へ。x[n][?]
ab = [[int(i) for i in input().split()] for i in range(n)]
# 0:weight 1:value

ab = sorted(ab,key=lambda x: x[1])

dp = np.zeros((n+1,t),int)
dp2 = np.zeros((n+1,t),int)

for i in range(n):
    w = ab[i][0]
    dp[i+1][w:] = np.fmax(dp[i][:-w] + ab[i][1], dp[i][w:])
    dp2[i+1][w:] = np.fmax(dp2[i][:-w] + ab[i][1],dp[i][w:] + ab[i][1], dp2[i][w:])
    dp[i+1][:w] = dp[i][:w]
    dp2[i+1][:w] = np.fmax(dp[i][:w] + ab[i][1], dp2[i][:w])

answer = np.amax(dp2)
print(answer)
### BUGGY CODE ###

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

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

u = UnionFind(n)
for i in range(m):
    x = xy[i][0]
    y = xy[i][1]
    u.union(x, y)

idxs = []
for i in range(1, n+1):
    idxs.append(u.find(i))

idx_dict = dict()
keys = []
for i in range(n):
    if idxs[i] not in keys:
        idx_dict[idxs[i]] = [i]
        keys.append(idxs[i])
    else:
        idx_dict[idxs[i]].append(i)

counter = 0
for k in keys:
    l = idx_dict[k]
    template = []
    for i in range(len(l)):
        template.append(p[l[i]] - 1)

    counter += len(set(l) & set(template))

print(counter)


### FIXED CODE ###

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

from collections import defaultdict
g = defaultdict(list)
for x, y in xy:
    x, y = x - 1, y - 1
    g[x].append(y)
    g[y].append(x)

visited = [0] * n
ans = 0

for i in range(n):
    if visited[i] == 0:
        q = [i]
        visited[i] = 1
        s = set([i])
        while q:
            cur = q.pop()
            for target in g[cur]:
                if visited[target] == 0:
                    visited[target] = 1
                    q.append(target)
                    s.add(target)

        ps = set()
        for j in s:
            ps.add(p[j] - 1)

        intersect = s & ps
        ans += len(list(intersect))
print(ans)
### BUGGY CODE ###

N, K = map(int, input().split())
h = list(map(int, input().split()))
 
DP = [0]
for i in range(N-1):
    act = float("inf")
    for k in range(K):
        if i-k < 0 : continue
        act = min(DP[-1-k] + abs(h[i-k]-h[i+1]) , act)
    DP += [act]
 
print(DP[-1])

### FIXED CODE ###

# B Frog 2

n, k = map(int, input().split())
h_list = [int(x) for x in input().split()]

dp = [float('Inf')] * n
dp[0] = 0

for i in range(n):
    for j in range(1,k+1,1):
        if i - j < 0:
            continue
        dp[i] = min(dp[i], dp[i-j] + abs(h_list[i-j]-h_list[i]))

        
print(dp[n-1])
### BUGGY CODE ###

NAB = input().split()

N = int(NAB[0])
A = int(NAB[1])
B = int(NAB[2])


list = []

for t in range(10**100):
	for i in range(A):
  		list.append('b')
	for i in range(B):  
  		list.append('r')
 
count = 0
for i in range(N):
  if list[i] == 'b':
    count += 1
    
print(count)

### FIXED CODE ###

NAB = input().split()

N = int(NAB[0])
A = int(NAB[1])
B = int(NAB[2])

kaisuu = N // (A+B)
amari = N % (A+B)

if kaisuu >= 10**100:
  solution = A ** (10**100)
else:
  if amari <= A:
  	solution = A * kaisuu + amari
  else:
    solution = A * kaisuu + A

print(solution)
### BUGGY CODE ###

from collections import deque
from sys import exit

N, M, K = [int(x) for x in input().split()]

a_book = [0]
for index, i in enumerate(input().split(), 1):
    if a_book[index-1] + int(i) <= K:
        a_book.append(a_book[index-1] + int(i))
    else:
        N = index - 1
        break

b_book = [0]
for index, i in enumerate(input().split(), 1):
    if b_book[index-1] + int(i) <= K:
        b_book.append(b_book[index-1] + int(i))
    else:
        M = index - 1
        break

search = deque()
check = {}

max_books = 0

for a_pos in range(N, -1, -1):
    a = a_book[a_pos]
    b_pos = 0
    for x in range(b_pos, M+1):
        if a + b_book[x] > K:
            break

        if max_books < a_pos + x:
            max_books = a_pos + x

print(max_books)


### FIXED CODE ###

from bisect import bisect_right
from time import time

N, M, K = [int(x) for x in input().split()]

a_book = [0]
for index, i in enumerate(input().split(), 1):
    if a_book[index-1] + int(i) <= K:
        a_book.append(a_book[index-1] + int(i))
    else:
        N = index - 1
        break

b_book = [0]
for index, i in enumerate(input().split(), 1):
    if b_book[index-1] + int(i) <= K:
        b_book.append(b_book[index-1] + int(i))
    else:
        M = index - 1
        break

check = {}

max_books = 0

for i, a in enumerate(a_book):
    b_pos = bisect_right(b_book, K - a)

    if max_books < b_pos - 1 + i:
        max_books = b_pos - 1 + i

print(max_books)
### BUGGY CODE ###

import math
n, k = list(map(int, input().split()))
A = list(map(int, input().split()))

for _ in range(k):
    B = [0] * n
    for i, a in enumerate(A):
        sta = math.ceil(i-a-0.5)
        end = math.floor(i+a+0.5)
        for j in range(max(0, sta), min(end+1, n)):
            B[j] += 1
    if A == B:
        A = B
        break
    A = B
print(' '.join(map(str, A)))

### FIXED CODE ###

N, K = list(map(int, input().split()))
A = list(map(int, input().split()))

dp = [0] * (N + 1)
for k in range(K):
    sta = [max(i-A[i], 0) for i in range(N)]
    end = [min(i+A[i]+1, N) for i in range(N)]
    for s in sta:
        dp[s] += 1
    for e in end:
        dp[e] -= 1
    for i in range(1, len(dp)-1):
        dp[i] += dp[i-1]
    B = dp[:-1]
    if A == B:
        break
    A = B
    dp = [0] * (N + 1)
 
print(' '.join(map(str, A)))
### BUGGY CODE ###

n = int(input())

a = list(map(int, input().split()))

for i in range(1, n+1):
  if a.count(i) == 0:
    del a [(i-1):]
    break
  else:
    index = a.index(i)
    del a[(i-1):index]

if len(a) == 0:
  print('-1')

else:
  print(n - len(a))


### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))

card = 1
cnt = 0

for i in a:
  if i == card:
    card += 1
  else:
    cnt += 1

if cnt == n:
  print('-1')

else:
  print(cnt)