Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game. 

The rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins this fight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins. 

You have to calculate how many fights will happen and who will win the game, or state that game won't end.


-----Input-----

First line contains a single integer n (2 ≤ n ≤ 10), the number of cards.

Second line contains integer k_1 (1 ≤ k_1 ≤ n - 1), the number of the first soldier's cards. Then follow k_1 integers that are the values on the first soldier's cards, from top to bottom of his stack.

Third line contains integer k_2 (k_1 + k_2 = n), the number of the second soldier's cards. Then follow k_2 integers that are the values on the second soldier's cards, from top to bottom of his stack.

All card values are different.


-----Output-----

If somebody wins in this game, print 2 integers where the first one stands for the number of fights before end of game and the second one is 1 or 2 showing which player has won.

If the game won't end and will continue forever output  - 1.


-----Examples-----
Input
4
2 1 3
2 4 2

Output
6 2
Input
3
1 2
2 1 3

Output
-1


-----Note-----

First sample:  [Image] 

Second sample:  [Image]

Difficulty: MEDIUM
Tags: Graph traversal

Game theory

Complete search
Skill types: Complete search

Starter code:

Solutions:
n = int(input())
s1 = [int(x) for x in input().split()]
s1.pop(0)
s2 = [int(x) for x in input().split()]
s2.pop(0)
c = 0
chk = [[False for x in range(11)] for x in range(11)]
while True:
	if c > 1000:
		print(-1)
		return
	if not s1 or not s2:
		print(c, 1 if not s2 else 2)
		return
	else:
		chk[s1[0]][s2[0]] = True
		if s1[0] > s2[0]:
			s1.append(s2[0])
			s1.append(s1[0])
			s1.pop(0)
			s2.pop(0)
		else:
			s2.append(s1[0])
			s2.append(s2[0])
			s1.pop(0)
			s2.pop(0)
		c += 1


n = int(input())
temp = list(map(int, input().split()))
k1 = temp[0]
a = temp[1:].copy()
temp = list(map(int, input().split()))
k2 = temp[0]
b = temp[1:].copy()
count = 0
l1 = len(a)
l2 = len(b)
while count < 1000:
	aTemp = a.pop(0)
	bTemp = b.pop(0)
	if aTemp > bTemp:
		a.append(bTemp)
		a.append(aTemp)
		l1 += 1
		l2 -= 1
	else:
		b.append(aTemp)
		b.append(bTemp)
		l2 += 1
		l1 -= 1
	count += 1
	if l1 == 0 or l2 == 0:
		break
if l1 == 0 or l2 == 0:
	print(count, '1' if l2 == 0 else '2')
else:
	print(-1)


t = int(input())
l = list(map(int, input().split()))
l1 = list(map(int, input().split()))
k1 = l.pop(0)
k2 = l1.pop(0)
game = 0
h = 0
len10 = 1
len20 = 1
while len(l) != 0 and len(l1) != 0:
	a = l.pop(0)
	b = l1.pop(0)
	if a > b:
		l.append(b)
		l.append(a)
	elif b > a:
		l1.append(a)
		l1.append(b)
	game += 1
	if game > 10000:
		h = 1
		break
	if len(l) == 0:
		len10 = 0
	if len(l1) == 0:
		len20 = 0
if h == 0:
	print(game, end=' ')
	if len20:
		print(2)
	if len10:
		print(1)
else:
	print(-1)


from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from collections import deque
from functools import cmp_to_key
import math
import heapq
import re

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	s = set()
	for p in range(2, n + 1):
		if prime[p]:
			s.add(p)
	return s

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	n = iin()
	k1 = ain()
	k2 = ain()
	d1 = deque(k1[1:])
	d2 = deque(k2[1:])
	k1 = k1[0]
	k2 = k2[0]
	a1 = deque([d1.copy()])
	a2 = deque([d2.copy()])
	flag = -1
	ans = 0
	while 1:
		ans += 1
		x1 = d1.popleft()
		x2 = d2.popleft()
		if x1 > x2:
			d1.append(x2)
			d1.append(x1)
		else:
			d2.append(x1)
			d2.append(x2)
		if len(d1) == 0:
			flag = 2
			break
		if len(d2) == 0:
			flag = 1
			break
		if d1 in a1 and d2 in a2:
			break
		a1.append(d1.copy())
		a2.append(d2.copy())
	if flag == -1:
		print(flag)
	else:
		print(ans, flag)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if os.getcwd() == 'D:\\code':
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
A = list(map(int, input().split()))
A.pop(0)
B = list(map(int, input().split()))
B.pop(0)
count = 0
while len(A) != 0 and len(B) != 0 and (count <= 10000):
	if A[0] < B[0]:
		B.append(A[0])
		B.append(B[0])
		B.pop(0)
		A.pop(0)
		count = count + 1
	elif A[0] > B[0]:
		A.append(B[0])
		A.append(A[0])
		A.pop(0)
		B.pop(0)
		count = count + 1
if count >= 10000:
	print(-1)
elif len(A) == 0:
	print(count, end=' ')
	print(2)
else:
	print(count, end=' ')
	print(1)


from math import *
from collections import deque
from copy import deepcopy
import sys

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def multi():
	return map(int, input().split())

def strmulti():
	return map(str, inp().split())

def lis():
	return list(map(int, inp().split()))

def lcm(a, b):
	return a * b // gcd(a, b)

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def stringlis():
	return list(map(str, inp().split()))

def out(var):
	sys.stdout.write(str(var))

def printlist(a):
	print(' '.join((str(a[i]) for i in range(len(a)))))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
n = int(input())
a = lis()
b = lis()
k1 = a[0]
k2 = b[0]
initiala = deepcopy(a[1:])
initialb = deepcopy(b[1:])
a = deque(a[1:])
b = deque(b[1:])
ans = 0
while True:
	if ans > 200:
		print(-1)
		exit(0)
	if len(a) == 0 or len(b) == 0:
		if len(a) == 0:
			print(ans, 2)
		elif len(b) == 0:
			print(ans, 1)
		exit(0)
	if a[0] > b[0]:
		num1 = a.popleft()
		num2 = b.popleft()
		a.append(num2)
		a.append(num1)
		ans += 1
	else:
		num1 = a.popleft()
		num2 = b.popleft()
		b.append(num1)
		b.append(num2)
		ans += 1


I = lambda : list(map(int, input().split()))
n = int(input())
d1 = I()[1:]
d2 = I()[1:]
states = set()
while 1:
	if d1[0] > d2[0]:
		d1 = d1[1:] + [d2[0], d1[0]]
		d2 = d2[1:]
	else:
		d2 = d2[1:] + [d1[0], d2[0]]
		d1 = d1[1:]
	if len(d2) == 0:
		print(len(states) + 1, 1)
		break
	if len(d1) == 0:
		print(len(states) + 1, 2)
		break
	state = ''.join(map(str, d1)) + '|' + ''.join(map(str, d2))
	if state in states:
		print(-1)
		break
	states.add(state)


n = int(input())
sol_1 = list(map(int, input().split()))
l1 = sol_1[0]
s1 = l1
sol_1 = sol_1[1:]
sol_2 = list(map(int, input().split()))
l2 = sol_2[0]
s2 = l2
sol_2 = sol_2[1:]
i = 0
j = 0
sol_11 = []
sol_22 = []
p = 10000
c = 0
while s1 != 0 and s2 != 0 and (p > 0):
	if i == len(sol_1):
		i = 0
		sol_1 = sol_11[:]
		sol_11 = []
	if j == len(sol_2):
		j = 0
		sol_2 = sol_22[:]
		sol_22 = []
	if sol_1[i] > sol_2[j]:
		sol_11.append(sol_2[j])
		sol_11.append(sol_1[i])
		s1 += 1
		s2 -= 1
	else:
		sol_22.append(sol_1[i])
		sol_22.append(sol_2[j])
		s2 += 1
		s1 -= 1
	i += 1
	j += 1
	c += 1
	p -= 1
if p == 0:
	print(-1)
elif s1 == 0:
	print(c, '2')
else:
	print(c, '1')


a = int(input())
x = list(map(int, input().split(' ')))[1:]
y = list(map(int, input().split(' ')))[1:]
num = 0
states = []
while len(x) > 0 and len(y) > 0:
	tx = x[0]
	ty = y[0]
	if tx > ty:
		x = x[1:] + [ty] + [tx]
		y = y[1:]
	else:
		y = y[1:] + [tx] + [ty]
		x = x[1:]
	num += 1
	states.append([x, y])
	if num > 10 ** 5:
		if [x, y] in states:
			print(-1)
			quit()
if x == []:
	print(num, 2)
else:
	print(num, 1)


from collections import deque
n = int(input())
l1 = deque(list(map(int, input().split()))[1:])
l2 = deque(list(map(int, input().split()))[1:])
res = 0
while l1 and l2:
	(c1, c2) = (l1.popleft(), l2.popleft())
	if res > 1000:
		break
	if c1 > c2:
		l1.append(c2)
		l1.append(c1)
	else:
		l2.append(c1)
		l2.append(c2)
	res += 1
if res > 1000:
	print(-1)
elif l1:
	print(res, 1)
else:
	print(res, 2)


n = int(input())
a1 = [int(x) for x in input().split()][1:]
a2 = [int(x) for x in input().split()][1:]
pos = []
i = 0
cur = [a1[1:], a2[1:]]
while not cur in pos and len(a1) > 0 and (len(a2) > 0):
	pos.append(cur)
	if a1[0] > a2[0]:
		t = a1[0]
		a1 = a1[1:]
		a1 += [a2[0], t]
		a2 = a2[1:]
	else:
		t = a2[0]
		a2 = a2[1:]
		a2 += [a1[0], t]
		a1 = a1[1:]
	cur = [a1[1:], a2[1:]]
	i += 1
if len(a1) == 0:
	print(i)
	print(2)
elif len(a2) == 0:
	print(i)
	print(1)
else:
	print(-1)


from collections import deque

def main():
	(n, d, ans1, ans2) = (int(input()), {}, 0, 0)
	dq1 = deque([int(i) for i in input().split()][1:])
	dq2 = deque([int(i) for i in input().split()][1:])
	while True:
		if (tuple(dq1), tuple(dq2)) in d:
			break
		else:
			d[tuple(dq1), tuple(dq2)] = 1
			(a, b) = (dq1.popleft(), dq2.popleft())
			ans1 += 1
			if a > b:
				dq1.append(b)
				dq1.append(a)
			else:
				dq2.append(a)
				dq2.append(b)
			if len(dq1) == 0:
				ans2 = 2
				break
			elif len(dq2) == 0:
				ans2 = 1
				break
	if ans2 == 0:
		print('-1')
	else:
		print(ans1, ans2)
main()


N = int(input())
l = list(map(int, input().split()))
k1 = l[0]
L = l[1:]
l = list(map(int, input().split()))
k2 = l[0]
R = l[1:]
se = set([])
se.add(tuple(L))
se.add(tuple(R))
ans = 0
while True:
	if len(L) == 0 or len(R) == 0:
		break
	top_L = L[0]
	top_R = R[0]
	L = L[1:]
	R = R[1:]
	if top_L > top_R:
		L = L + [top_R, top_L]
	else:
		R = R + [top_L, top_R]
	if tuple(L) in se and tuple(R) in se:
		print(-1)
		exit()
	se.add(tuple(L))
	se.add(tuple(R))
	ans += 1
if len(L) == 0:
	print('{} {}'.format(ans, 2))
else:
	print('{} {}'.format(ans, 1))


n = int(input())
k1 = list(map(int, input().split()))[1:]
k2 = list(map(int, input().split()))[1:]
kh = 0
while k1 and k2:
	if kh > 5000:
		print(-1)
		exit()
	kh += 1
	(a, b) = (k1.pop(0), k2.pop(0))
	if a > b:
		k1 += [b, a]
	else:
		k2 += [a, b]
if k1:
	print(kh, 1)
else:
	print(kh, 2)


from sys import stdin
from collections import defaultdict
import sys
from collections import deque
import time
sys.setrecursionlimit(15000)

def reverse(arr):
	c = []
	for i in range(len(arr) - 1, 0, -1):
		c.append(arr[i])
	return c
n = int(stdin.readline().strip())
arr1 = list(map(int, stdin.readline().split()))
arr2 = list(map(int, stdin.readline().split()))
arr1 = reverse(arr1)
first = deque(arr1)
arr2 = reverse(arr2)
second = deque(arr2)
count = 0
initial = time.time()
while time.time() - initial < 1.48 and len(first) > 0 and (len(second) > 0):
	count += 1
	one = first.pop()
	two = second.pop()
	if one >= two:
		first.appendleft(two)
		first.appendleft(one)
	else:
		second.appendleft(one)
		second.appendleft(two)
if len(first) == 0 and len(second) > 0:
	print(count, 2)
elif len(first) > 0 and len(second) == 0:
	print(count, 1)
else:
	print(-1)


n = input()
input_one = input()
input_two = input()
player1 = [int(x) for x in input_one.split(' ')]
player2 = [int(x) for x in input_two.split(' ')]
player2.pop(0)
player1.pop(0)
count = 0
state = []
state.append(player1[:])
state.append(player2[:])
while True:
	a = player1.pop(0)
	b = player2.pop(0)
	if a > b:
		count += 1
		player1.append(b)
		player1.append(a)
	else:
		count += 1
		player2.append(a)
		player2.append(b)
	if not player1:
		print(str(count) + ' ' + str(2))
		break
	if not player2:
		print(str(count) + ' ' + str(1))
		break
	if player1 in state and player2 in state:
		print('-1')
		break
	else:
		state.append(player1[:])
		state.append(player2[:])


n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
d = {}
d[tuple(a), tuple(b)] = True
res = 0
while len(a) and len(b):
	res += 1
	if a[0] > b[0]:
		a.extend([b[0], a[0]])
	else:
		b.extend([a[0], b[0]])
	a.pop(0)
	b.pop(0)
	if (tuple(a), tuple(b)) in d:
		print(-1)
		exit()
	d[tuple(a), tuple(b)] = True
print(res, 1 + (len(a) == 0))


import sys
from collections import *
import math
input = sys.stdin.readline
n = int(input())
arr1 = [int(x) for x in input().split()]
arr2 = [int(x) for x in input().split()]
h = Counter()
k1 = arr1[0]
q1 = deque(arr1[1:])
k2 = arr2[0]
q2 = deque(arr2[1:])
count = 0
h[tuple(q1)] = 1
h[tuple(q2)] = 1
while q1 and q2:
	x = q1.popleft()
	y = q2.popleft()
	if x > y:
		q1.append(y)
		q1.append(x)
	else:
		q2.append(x)
		q2.append(y)
	count += 1
	if h[tuple(q1)] == 1 and h[tuple(q2)] == 1:
		count = -1
		break
	h[tuple(q1)] = 1
	h[tuple(q2)] = 1
if count == -1:
	print(count)
elif q1:
	print(count, 1)
else:
	print(count, 2)


n = int(input())
tmp = [int(i) for i in input().split()]
an = tmp[0]
a = tmp[1:]
tmp = [int(i) for i in input().split()]
bn = tmp[0]
b = tmp[1:]
count = 0
never = 0
while True:
	av = a.pop(0)
	bv = b.pop(0)
	if av > bv:
		a.append(bv)
		a.append(av)
	else:
		b.append(av)
		b.append(bv)
	count += 1
	if len(a) == 0 or len(b) == 0:
		break
	if count > 1000000:
		never = 1
		break
if never == 0:
	winner = 1
	if len(a) == 0:
		winner = 2
	print(str(count) + ' ' + str(winner))
else:
	print(-1)


n = int(input())
k1 = list(map(int, input().split()))[1:]
k2 = list(map(int, input().split()))[1:]
k1copy = k1.copy()
k2copy = k2.copy()
result = True
fight = 0
winner = 0
i = 0
while True:
	first = k1[0]
	second = k2[0]
	k1.pop(0)
	k2.pop(0)
	fight += 1
	i += 1
	if first > second:
		k1.append(second)
		k1.append(first)
	elif second > first:
		k2.append(first)
		k2.append(second)
	else:
		fight -= 1
		continue
	if len(k1) == 0:
		winner = 2
		break
	elif len(k2) == 0:
		winner = 1
		break
	if k1 == k1copy and k2 == k2copy:
		result = False
		break
	if i > 10000:
		result = False
		break
if result:
	print(fight, winner)
else:
	print(-1)


ll = lambda : map(int, input().split())
t = lambda : int(input())
ss = lambda : input()
lx = lambda x: map(int, input().split(x))
yy = lambda : print('YES')
nn = lambda : print('NO')
from math import log10, log2, ceil, factorial as fac, gcd, inf, sqrt, log
from bisect import bisect_right as br, bisect_left as bl
from collections import Counter
mod = 10 ** 9 + 7

def f():
	n = t()
	(k1, *a) = list(ll())
	(k2, *b) = list(ll())
	q = []
	c = 0
	q.append([a.copy(), b.copy()])
	while len(a) and len(b):
		c += 1
		(x, y) = (a.pop(0), b.pop(0))
		if x > y:
			a.append(y)
			a.append(x)
		else:
			b.append(x)
			b.append(y)
		if [a, b] not in q:
			q.append([a.copy(), b.copy()])
		else:
			print(-1)
			break
	else:
		print(c, [1, 2][len(b) > 0])
f()


from sys import stdin
from collections import deque
n = int(stdin.readline())
k1nums = deque(map(int, stdin.readline().split()))
k2nums = deque(map(int, stdin.readline().split()))
k1nums.popleft()
k2nums.popleft()
flag = 1
ng = 0
loopcount = 1000
while k1nums and k2nums and loopcount:
	loopcount -= 1
	(top1, top2) = (k1nums.popleft(), k2nums.popleft())
	if top1 > top2:
		k1nums.append(top2)
		k1nums.append(top1)
	else:
		k2nums.append(top1)
		k2nums.append(top2)
	ng += 1
if loopcount:
	if not k1nums:
		print(ng, 2)
	else:
		print(ng, 1)
else:
	print(-1)


input()
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
c = 0
for i in range(100000):
	if not a or not b:
		print(c, end=' ')
		print(2 if not a else 1)
		break
	x = a.pop(0)
	y = b.pop(0)
	if x > y:
		a.append(y)
		a.append(x)
	else:
		b.append(x)
		b.append(y)
	c += 1
else:
	print(-1)


n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
t1 = l1[1:]
t2 = l2[1:]
cnt = 0
while cnt < 10000:
	TopT1 = t1.pop(0)
	TopT2 = t2.pop(0)
	if TopT1 < TopT2:
		t2.append(TopT1)
		t2.append(TopT2)
	else:
		t1.append(TopT2)
		t1.append(TopT1)
	cnt += 1
	if len(t1) <= 0:
		print(cnt, '2')
		exit(0)
	elif len(t2) <= 0:
		print(cnt, '1')
		exit(0)
	if t1 == l1[1:] and t2 == l2[1:]:
		print(-1)
		exit(0)
print(-1)


n = int(input())
from collections import deque
k1 = list(map(int, input().split()))
k1 = deque(k1[1:])
k2 = list(map(int, input().split()))
k2 = deque(k2[1:])
a = []
b = []
count = 0
while list(k1) not in a or list(k2) not in b:
	a.append(list(k1))
	b.append(list(k2))
	if k1[0] > k2[0]:
		k1.append(k2[0])
		k1.append(k1[0])
		k1.popleft()
		k2.popleft()
	else:
		k2.append(k1[0])
		k2.append(k2[0])
		k1.popleft()
		k2.popleft()
	count += 1
	if len(k2) == 0:
		print(count, 1)
		exit(0)
	elif len(k1) == 0:
		print(count, 2)
		exit(0)
print(-1)


n = int(input())
a1 = list(map(int, input().split()))
p = a1[0]
a1.pop(0)
a2 = list(map(int, input().split()))
q = a2[0]
a2.pop(0)
c = 0
while len(a1) > 0 and len(a2) > 0:
	if a1[0] > a2[0]:
		a1.append(a2[0])
		a1.append(a1[0])
		a1.pop(0)
		a2.pop(0)
		c += 1
	else:
		a2.append(a1[0])
		a2.append(a2[0])
		a1.pop(0)
		a2.pop(0)
		c += 1
	if c > 100000:
		print(-1)
		exit()
if len(a1) > len(a2):
	z = 1
else:
	z = 2
print(c, z)


n = int(input())
l = list(map(int, input().split()))
l.pop(0)
l1 = list(map(int, input().split()))
l1.pop(0)
c = 0
while l and l1:
	c += 1
	a = l.pop(0)
	b = l1.pop(0)
	if a > b:
		l.append(b)
		l.append(a)
	elif a < b:
		l1.append(a)
		l1.append(b)
	if c > 1000:
		break
if c > 1000:
	print(-1)
elif len(l) < len(l1):
	print(c, 2)
else:
	print(c, 1)


n = int(input())
k1 = input().strip().split()
k2 = input().strip().split()
k1 = k1[1:]
k2 = k2[1:]
mema = []
memb = []
r = 0
while k1 != [] and k2 != []:
	r += 1
	mema.append(k1[:])
	memb.append(k2[:])
	a = k1[0]
	del k1[0]
	b = k2[0]
	del k2[0]
	if int(a) > int(b):
		k1.append(b)
		k1.append(a)
	elif int(b) > int(a):
		k2.append(a)
		k2.append(b)
	if k1 == []:
		print(r, 2)
	elif k2 == []:
		print(r, 1)
	if k1 in mema and k2 in memb:
		print(-1)
		break


n = int(input())
temparr = input()
temparr = temparr.split()
player1 = []
player2 = []
for (j, i) in enumerate(temparr):
	if j == 0:
		continue
	player1.append(int(i))
temparr = input()
temparr = temparr.split()
for (j, i) in enumerate(temparr):
	if j == 0:
		continue
	player2.append(int(i))
if len(player1) == 0:
	print('0 2')
elif len(player2) == 0:
	print('0 1')
else:
	flag = 0
	count = 0
	while True:
		if len(player1) == 0:
			print(str(count) + ' 2')
			flag = 1
			break
		if len(player2) == 0:
			print(str(count) + ' 1')
			flag = 1
			break
		if count == 200:
			break
		if player1[0] > player2[0]:
			highercard = player1[0]
			lowercard = player2[0]
			player1.pop(0)
			player2.pop(0)
			player1.append(lowercard)
			player1.append(highercard)
		else:
			highercard = player2[0]
			lowercard = player1[0]
			player1.pop(0)
			player2.pop(0)
			player2.append(lowercard)
			player2.append(highercard)
		count += 1
	if flag == 0:
		print(-1)


n = int(input())
ak = input().split(' ')
ak.remove(ak[0])
bk = input().split(' ')
bk.remove(bk[0])
c = 0
d = 0
for i in range(len(bk)):
	while len(ak) > 0 and len(bk) > 0 and (c < 1000):
		if int(ak[i]) > int(bk[i]):
			s = ak[i]
			ak.append(bk[i])
			ak.remove(ak[i])
			ak.append(s)
			bk.remove(bk[i])
			c = c + 1
		else:
			t = bk[i]
			bk.append(ak[i])
			bk.remove(bk[i])
			bk.append(t)
			ak.remove(ak[i])
			c = c + 1
if c > 999:
	print(-1)
elif len(ak) > len(bk):
	print(c, 1)
else:
	print(c, 2)


N = int(input())
A = list(map(int, input().rstrip().split()))
B = list(map(int, input().rstrip().split()))
initA = A[1:len(A)]
initB = B[1:len(B)]
initA.reverse()
initB.reverse()
tempA = []
tempB = []
tempA.extend(initA)
tempB.extend(initB)
count = 0
while 1 != 0:
	if tempA[-1] > tempB[-1]:
		tempA.insert(0, tempB.pop())
		tempA.insert(0, tempA.pop())
	else:
		tempB.insert(0, tempA.pop())
		tempB.insert(0, tempB.pop())
	if count == 100:
		temptB = []
		temptB.extend(tempB)
		temptA = []
		temptA.extend(tempA)
	if tempB == initB and tempA == initA:
		print(-1)
		break
	elif count > 100 and tempA == temptA and (tempB == temptB):
		print(-1)
		break
	elif len(tempB) == 0:
		print(count + 1, 1)
		break
	elif len(tempA) == 0:
		print(count + 1, 2)
		break
	else:
		count += 1


n = int(input())
h1 = list(map(int, input().split()))
h2 = list(map(int, input().split()))
h1.pop(0)
h2.pop(0)
s = set()
res = 0
while len(h1) != 0 and len(h2) != 0:
	a = tuple([tuple(h1), tuple(h2)])
	if a not in s:
		s.add(a)
	else:
		print(-1)
		exit()
	c1 = h1.pop(0)
	c2 = h2.pop(0)
	if c1 > c2:
		h1 += [c2, c1]
	else:
		h2 += [c1, c2]
	res += 1
if len(h1) == 0:
	print(str(res) + ' 2')
else:
	print(str(res) + ' 1')


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
n = Int()
a = array()[1:]
b = array()[1:]
ina = a[:]
inb = b[:]
c = 0
while True:
	c += 1
	if a[0] > b[0]:
		e = b.pop(0)
		e1 = a.pop(0)
		a.append(e)
		a.append(e1)
	elif a[0] < b[0]:
		e = a.pop(0)
		e1 = b.pop(0)
		b.append(e)
		b.append(e1)
	if len(a) == 0:
		print(c, 2)
		exit()
	elif len(b) == 0:
		print(c, 1)
		exit()
	if c == 20 * n:
		print(-1)
		exit()


n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
i = 0
g = 1000000
while i < g and len(a) > 0 and (len(b) > 0):
	if a[0] < b[0]:
		b = b[1:] + a[:1] + b[:1]
		a = a[1:]
	else:
		a = a[1:] + b[:1] + a[:1]
		b = b[1:]
	i += 1
if i == g:
	print(-1)
elif len(a) == 0:
	print(i, 2)
else:
	print(i, 1)


def solve(st1, st2):
	L = []
	s1 = st1[:]
	s2 = st2[:]
	flag = -1
	fights = 0
	while [s1, s2] not in L:
		x1 = s1[:]
		x2 = s2[:]
		L.append([x1, x2])
		if len(s1) == 0:
			flag = 2
			break
		elif len(s2) == 0:
			flag = 1
			break
		if s1[0] > s2[0]:
			x = s2.pop(0)
			y = s1.pop(0)
			s1.append(x)
			s1.append(y)
		elif s1[0] < s2[0]:
			x = s2.pop(0)
			y = s1.pop(0)
			s2.append(y)
			s2.append(x)
		fights += 1
	if flag == -1:
		print(flag)
	else:
		print(fights, flag)
N = int(input())
stack1 = list(map(int, input().split()))
stack2 = list(map(int, input().split()))
stack1.pop(0)
stack2.pop(0)
solve(stack1, stack2)


from sys import stdin, stdout
from collections import deque
input = stdin.readline

def main():
	t = 1

	def pos(d1, d2):
		return int(''.join(map(str, list(d1) + list(d2))))
	for i in range(t):
		n = int(input())
		ai = list(map(int, input().split()))[1:]
		ai2 = list(map(int, input().split()))[1:]
		d1 = deque()
		d2 = deque()
		for i in ai:
			d1.appendleft(i)
		for i in ai2:
			d2.appendleft(i)
		p = {}

		def action():
			(temp, temp2) = (d1.pop(), d2.pop())
			if temp > temp2:
				d1.appendleft(temp2)
				d1.appendleft(temp)
			else:
				d2.appendleft(temp)
				d2.appendleft(temp2)
		ans = 0
		ans2 = 0
		while True:
			ans += 1
			action()
			if len(d1) == 0:
				ans2 = 2
				break
			if len(d2) == 0:
				ans2 = 1
				break
			temp = pos(d1, d2)
			if temp in p:
				print(-1)
				return
			p[temp] = 1
		print(ans, ans2)
main()


import collections
input()
fights = 0
player1 = collections.deque(map(int, input().split()))
player2 = collections.deque(map(int, input().split()))
player1.popleft()
player2.popleft()
while len(player1) != 0 and len(player2) != 0:
	fights += 1
	if fights > 10000:
		print(-1)
		exit(0)
	card1 = player1.popleft()
	card2 = player2.popleft()
	if card1 > card2:
		player1.append(card2)
		player1.append(card1)
	else:
		player2.append(card1)
		player2.append(card2)
if len(player1) == 0:
	print(fights, 2)
else:
	print(fights, 1)


n = int(input())
cards1 = list(map(int, input().split()))
cards2 = list(map(int, input().split()))
k1 = cards1[0]
k2 = cards2[0]
cards1 = cards1[1:]
cards2 = cards2[1:]
c = 0
f = 0
while True:
	a = cards1.pop(0)
	b = cards2.pop(0)
	if a < b:
		cards2.append(a)
		cards2.append(b)
		c += 1
	else:
		cards1.append(b)
		cards1.append(a)
		c += 1
	if c > 500:
		f = 1
		break
	if len(cards1) == 0 or len(cards2) == 0:
		break
if f == 1:
	print(-1)
else:
	if len(cards1) > 0:
		win = 1
	else:
		win = 2
	print(c, win)


import sys
input = sys.stdin.readline
from math import ceil, floor, factorial

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
n = int(input())
a = int_array()
b = int_array()
k1 = a[0]
a = a[1:]
k2 = b[0]
b = b[1:]
count = 0
f = 0
won = 2
while 1:
	if not a or not b:
		if not a:
			won = 2
		else:
			won = 1
		f = 1
		break
	count += 1
	x = a.pop(0)
	y = b.pop(0)
	if x > y:
		a.append(y)
		a.append(x)
	else:
		b.append(x)
		b.append(y)
	if count == 100000.0:
		break
if f:
	print(*(count, won))
else:
	print(-1)


x = int(input())
A = list(map(int, input().split()))
A = A[1:]
D = A
B = list(map(int, input().split()))
B = B[1:]
E = B
C = []
count = 0
num = 1000
while num > 0:
	if count == 999:
		state = 10000
		break
	state = -100
	if A == C:
		state = 10
		break
	if B == C:
		state = 100
		break
	if A[0] > B[0]:
		A.append(B[0])
		A.append(A[0])
		A = A[1:]
		B = B[1:]
		count = count + 1
		state = 0
		num = num - 1
	if state != 0:
		if B[0] > A[0]:
			B.append(A[0])
			B.append(B[0])
			B = B[1:]
			A = A[1:]
			count = count + 1
			num = num - 1
if state == 10:
	print(count, 2)
if state == 100:
	print(count, 1)
if state == 10000:
	print(-1)


import math
import time
n = int(input())
onecards = input().split()
onecards.pop(0)
for i in range(len(onecards)):
	onecards[i] = int(onecards[i])
twocards = input().split()
twocards.pop(0)
for i in range(len(twocards)):
	twocards[i] = int(twocards[i])
startone = []
for i in range(len(onecards)):
	startone.append(onecards[i])
onelength = len(startone)
starttwo = []
for i in range(len(twocards)):
	starttwo.append(twocards[i])
twolength = len(starttwo)
start = time.time()
plays = 0
while True:
	cone = onecards.pop(0)
	ctwo = twocards.pop(0)
	if cone > ctwo:
		onecards.append(ctwo)
		onecards.append(cone)
	else:
		twocards.append(cone)
		twocards.append(ctwo)
	plays = plays + 1
	if len(twocards) == 0:
		print(str(plays) + ' 1')
		break
	if len(onecards) == 0:
		print(str(plays) + ' 2')
		break
	if onecards == startone and twocards == starttwo or plays > 362880:
		print(-1)
		break
finish = time.time()


def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1] * (n + 1)
	(arr[0], arr[1], i) = (0, 0, 2)
	while i * i <= n:
		if arr[i] == 1:
			j = i + i
			while j <= n:
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans

def nc2(x):
	if x == 1:
		return 0
	else:
		return x * (x - 1) // 2

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def mex(li):
	check = [0] * 1001
	for i in li:
		check[i] += 1
	for i in range(len(check)):
		if check[i] == 0:
			return i

def sumdigits(n):
	ans = 0
	while n != 0:
		ans += n % 10
		n //= 10
	return ans
from math import *
from collections import deque
max_steps = 100005
for _ in range(1):
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	s1 = a[0]
	s2 = b[0]
	a = a[1:]
	c = a[:]
	d = b[1:]
	b = d[:]
	cnt = 0
	steps = 0
	while len(a) != 0 and len(b) != 0:
		steps += 1
		if steps > max_steps:
			break
		(val1, val2) = (a[0], b[0])
		if val1 < val2:
			a = a[1:]
			b = b[1:]
			b.append(val1)
			b.append(val2)
			cnt += 1
		else:
			a = a[1:]
			b = b[1:]
			a.append(val2)
			a.append(val1)
			cnt += 1
		if a == c and b == d:
			break
	if len(a) == 0:
		print(cnt, 2)
	elif len(b) == 0:
		print(cnt, 1)
	else:
		print(-1)


n = input()
a = list(map(int, input().split()[1:]))
b = list(map(int, input().split()[1:]))
copy_b = b[:]
copy_a = a[:]
i = 0
while True:
	a_x = a.pop(0)
	b_x = b.pop(0)
	if a_x > b_x:
		a.append(b_x)
		a.append(a_x)
	else:
		b.append(a_x)
		b.append(b_x)
	if len(a) == 0:
		print(i + 1, 2)
		break
	if len(b) == 0:
		print(i + 1, 1)
		break
	if copy_a == a and copy_b == b and (i != 0) or i > 10000:
		print(-1)
		break
	i += 1


import logging
import sys
from collections import deque
logger_cagada = None
nivel_log = logging.ERROR

def queue_a_tupla(q):
	tupla = tuple(list(q))
	logger_cagada.debug('la tupla de {} es {}'.format(q, tupla))
	return tupla

def soldado_del_amor_barajea(pila1, pila2, comps_ya_vistas):
	if (queue_a_tupla(pila1), queue_a_tupla(pila2)) in comps_ya_vistas:
		return False
	comps_ya_vistas.add((queue_a_tupla(pila1), queue_a_tupla(pila2)))
	elem1 = pila1.popleft()
	elem2 = pila2.popleft()
	logger_cagada.debug('comparando {} con {}'.format(elem1, elem2))
	if elem1 > elem2:
		pila1.append(elem2)
		pila1.append(elem1)
	else:
		pila2.append(elem1)
		pila2.append(elem2)
	return True

def soldado_del_amor_core(nums1, nums2):
	q1 = deque(nums1)
	q2 = deque(nums2)
	num_vueltas = 0
	comps_ya_vistas = set()
	conti = True
	while conti and q1 and q2:
		logger_cagada.debug('la q1 {} la q2 {}'.format(q1, q2))
		conti = soldado_del_amor_barajea(q1, q2, comps_ya_vistas)
		num_vueltas += 1
	if not conti:
		return (None, None)
	if not q1:
		return (num_vueltas, 2)
	else:
		return (num_vueltas, 1)

def soldado_del_amor_main():
	lineas = list(sys.stdin)
	nums1 = [int(x) for x in lineas[1].strip().split(' ')]
	nums2 = [int(x) for x in lineas[2].strip().split(' ')]
	(n_v, g) = soldado_del_amor_core(nums1[1:], nums2[1:])
	if n_v:
		print('{} {}'.format(n_v, g))
	else:
		print('-1')
FORMAT = '[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s'
logging.basicConfig(level=nivel_log, format=FORMAT)
logger_cagada = logging.getLogger('asa')
logger_cagada.setLevel(nivel_log)
soldado_del_amor_main()


from collections import deque
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
a = a[1:]
b = b[1:]
a = deque(a)
b = deque(b)
k = 0
winner = 0
while 1:
	if len(a) == 0:
		winner = 2
		break
	elif len(b) == 0:
		winner = 1
		break
	firstcard = a.popleft()
	secondcard = b.popleft()
	if firstcard < secondcard:
		b.append(firstcard)
		b.append(secondcard)
	else:
		a.append(secondcard)
		a.append(firstcard)
	k += 1
	if k >= 10 ** 7:
		break
if winner == 0:
	print(-1)
else:
	print(k, winner)


def solve(n, playerA, playerB):
	round = 0
	compared = {}
	playerA.pop(0)
	playerB.pop(0)
	while True:
		if len(playerA) == 0:
			print(round, 2)
			return
		elif len(playerB) == 0:
			print(round, 1)
			return
		else:
			currentStruc = [playerA.copy(), playerB.copy()]
			cardA = playerA.pop(0)
			cardB = playerB.pop(0)
			if cardA not in compared:
				compared[cardA] = [currentStruc]
			else:
				for arr in compared[cardA]:
					if arr == currentStruc:
						print(-1)
						return
				compared[cardA].append(currentStruc)
			if cardA > cardB:
				playerA.append(cardB)
				playerA.append(cardA)
			else:
				playerB.append(cardA)
				playerB.append(cardB)
			round += 1
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
solve(n, a, b)


from collections import deque
cache = {}
N = int(input())
left = deque([int(i) for i in input().split()][1:])
right = deque([int(i) for i in input().split()][1:])

def next(state):
	cards = (state[0].popleft(), state[1].popleft())
	appendto = max(cards) == cards[1]
	state[appendto].extend((cards[not appendto], cards[appendto]))
	return state
state = (left, right)
f = 0
while len(state[0]) and len(state[1]):
	a = (tuple(state[0]), tuple(state[1]))
	if a in cache:
		break
	cache[a] = True
	state = next(state)
	f += 1
else:
	print(f, int(len(state[0]) == 0) + 1)
	exit(0)
print(-1)


from collections import *
n = int(input())
li1 = list(map(int, input().split(' ')))
li2 = list(map(int, input().split(' ')))
st1 = deque(li1[1:])
st2 = deque(li2[1:])
li1 = deque(li1[1:])
li2 = deque(li2[1:])
checked = []
temp = (st1.copy(), st2.copy())
checked.append(temp)
p1 = st1.popleft()
p2 = st2.popleft()
if p1 > p2:
	st1.append(p2)
	st1.append(p1)
else:
	st2.append(p1)
	st2.append(p2)
res = 0
count = 1
while True:
	if len(st2) == 0:
		res = 1
		break
	if len(st1) == 0:
		res = 2
		break
	temp = (st1.copy(), st2.copy())
	if temp in checked:
		break
	checked.append(temp)
	p1 = st1.popleft()
	p2 = st2.popleft()
	if p1 > p2:
		st1.append(p2)
		st1.append(p1)
	else:
		st2.append(p1)
		st2.append(p2)
	count += 1
if res == 0:
	print(-1)
	quit()
print(count, res)


from collections import *
n = int(input())
(a1, a2) = [deque(map(int, input().split())) for i in range(2)]
(k1, k2, visit) = (a1.popleft(), a2.popleft(), defaultdict(int))
(state, c) = ((tuple(a1), tuple(a2)), 0)
while not visit[state] and k1 and k2:
	(n1, n2) = (a1.popleft(), a2.popleft())
	k1 -= 1
	k2 -= 1
	if n1 > n2:
		a1.extend([n2, n1])
		k1 += 2
	else:
		a2.extend([n1, n2])
		k2 += 2
	visit[state] = 1
	state = (tuple(a1), tuple(a2))
	c += 1
if k1 == 0:
	print(c, 2)
elif k2 == 0:
	print(c, 1)
else:
	print(-1)


from collections import deque
t = int(input())
arr = [int(x) for x in input().split()]
arr1 = [int(x) for x in input().split()]
q1 = deque()
for i in range(1, len(arr)):
	q1.append(arr[i])
q2 = deque()
for i in range(1, len(arr1)):
	q2.append(arr1[i])
(cnt, c) = (0, 0)
while len(q1) > 0 and len(q2) > 0:
	x = q1.popleft()
	y = q2.popleft()
	cnt += 1
	if x > y:
		q1.append(y)
		q1.append(x)
	else:
		q2.append(x)
		q2.append(y)
	if arr == q2 and arr1 == q1:
		c = 1
		break
	elif cnt > 1000000:
		c = 1
		break
if len(q1) == 0:
	print(cnt, 2)
elif c == 1:
	print(-1)
else:
	print(cnt, 1)


n = int(input())
l = list(map(int, input().split()))[1:]
k = list(map(int, input().split()))[1:]
(a, b) = (l[:], k[:])
ans = 0
while len(l) and len(k) and (ans != -1) and (ans < 1000000):
	(v, s) = (l[0], k[0])
	(l, k) = (l[1:], k[1:])
	if v > s:
		l += [s, v]
	else:
		k += [v, s]
	ans += 1
	if ans != 1 and (a == l and b == k or (a == k and b == l)):
		ans = -1
if ans == -1 or (len(k) and len(l)):
	print(-1)
elif len(l) == 0:
	print(ans, 2)
else:
	print(ans, 1)


from collections import deque

def serialize(d):
	l = ''
	for e in d:
		l += str(e)
	return l

def hash(d1, d2):
	return serialize(d1) + ':' + serialize(d2)

def main():
	n = int(input())
	stack1 = deque(map(int, input().split()))
	stack2 = deque(map(int, input().split()))
	(stack1.popleft(), stack2.popleft())
	states = set()
	states.add(hash(stack1, stack2))
	moves = 0
	while len(stack1) > 0 and len(stack2) > 0:
		(card1, card2, moves) = (stack1.popleft(), stack2.popleft(), moves + 1)
		if card1 > card2:
			stack1.append(card2)
			stack1.append(card1)
		else:
			stack2.append(card1)
			stack2.append(card2)
		newState = hash(stack1, stack2)
		if newState in states:
			break
		states.add(newState)
	(s1, s2) = (len(stack1), len(stack2))
	if s1 > 0 and s2 == 0:
		print(moves, 1)
	elif s2 > 0 and s1 == 0:
		print(moves, 2)
	else:
		print(-1)
main()


import sys
import collections

def get_code(first_cards, second_cards):
	c1 = 0
	for (i, card) in enumerate(first_cards):
		c1 += (card - 1) * 10 ** i
	c2 = 0
	for (i, card) in enumerate(second_cards):
		c2 += (card - 1) * 10 ** i
	return (c1, c2)

def main():
	n = int(sys.stdin.readline())
	first_cards = collections.deque(reversed(list(map(int, sys.stdin.readline().split()))[1:]))
	second_cards = collections.deque(reversed(list(map(int, sys.stdin.readline().split()))[1:]))
	existing_states = set()
	number_of_fights = 0
	while first_cards and second_cards:
		code = (tuple(first_cards), tuple(second_cards))
		if code in existing_states:
			print(-1)
			return
		existing_states.add(code)
		if first_cards[-1] > second_cards[-1]:
			first_cards.appendleft(second_cards.pop())
			first_cards.appendleft(first_cards.pop())
		else:
			second_cards.appendleft(first_cards.pop())
			second_cards.appendleft(second_cards.pop())
		number_of_fights += 1
	print('%d %d' % (number_of_fights, 1 if not second_cards else 2))
main()


n = int(input())
x = input().split()
y = input().split()
player_1 = []
player_2 = []
memory = []
aux_1 = []
aux_2 = []
for card in range(int(x[0])):
	player_1.append(int(x[card + 1]))
	aux_1.append(int(x[card + 1]))
for card in range(int(y[0])):
	player_2.append(int(y[card + 1]))
	aux_2.append(int(y[card + 1]))
memory.append((aux_1, aux_2))
condition = False
counter = 0
while len(player_1) > 0 and len(player_2) > 0 and (not condition):
	(c1, c2) = (player_1.pop(0), player_2.pop(0))
	if c1 > c2:
		player_1.append(c2)
		player_1.append(c1)
	else:
		player_2.append(c1)
		player_2.append(c2)
	aux_1 = []
	aux_2 = []
	if (player_1, player_2) in memory:
		condition = True
		break
	for card in player_1:
		aux_1.append(card)
	for card in player_2:
		aux_2.append(card)
	memory.append((aux_1, aux_2))
	counter += 1
if not condition:
	answer = str(counter)
	if len(player_1) == 0:
		answer += ' 2'
	else:
		answer += ' 1'
else:
	answer = '-1'
print(answer)


n = int(input())
l1 = list(map(int, input().split()))
l1.remove(l1[0])
l2 = list(map(int, input().split()))
l2.remove(l2[0])
(a, b, c, d, l3, l4) = (0, 0, 0, 0, [l1[:]], [l2[:]])
while len(l1) != 0 and len(l2) != 0:
	if l1[0] > l2[0]:
		(a, d) = (l1[0], l2[0])
		l1.remove(l1[0])
		l2.remove(l2[0])
		l1.append(d)
		l1.append(a)
	else:
		(a, d) = (l2[0], l1[0])
		l2.remove(l2[0])
		l1.remove(l1[0])
		l2.append(d)
		l2.append(a)
	b += 1
	if l1 not in l3 or l2 not in l4:
		l3.append(l1[:])
		l4.append(l2[:])
	else:
		c = 1
		break
if c == 0:
	if len(l1) == 0:
		print(str(b) + ' 2')
	else:
		print(str(b) + ' 1')
else:
	print(-1)


from collections import deque
n = int(input())
a1 = deque(map(int, input().split()))
a1.popleft()
a2 = deque(map(int, input().split()))
a2.popleft()
cnt = 0
while len(a1) != 0 and len(a2) != 0 and (cnt <= 1000):
	(s1, s2) = (a1.popleft(), a2.popleft())
	if s1 == s2:
		continue
	elif s1 > s2:
		a1.append(s2)
		a1.append(s1)
	elif s2 > s1:
		a2.append(s1)
		a2.append(s2)
	cnt += 1
if cnt >= 1000:
	print('-1')
else:
	print(cnt, end=' ')
	if len(a1) == 0:
		print(2)
	else:
		print(1)


def all_equal(arr, a):
	for i in range(len(a)):
		if check_equal(arr, a[i]):
			return True
	return False

def check_equal(a, b):
	if len(a) != len(b):
		return False
	for i in range(len(a)):
		if a[i] != b[i]:
			return False
	return True
n = int(input())
k1 = [int(i) for i in input().split()]
k2 = [int(i) for i in input().split()]
a = k1[1:]
k1 = k1[0]
b = k2[1:]
k2 = k2[0]
temp_a = a[1:]
temp_b = b[1:]
if a[0] > b[0]:
	temp_a.append(b[0])
	temp_a.append(a[0])
else:
	temp_b.append(a[0])
	temp_b.append(b[0])
a = [a]
b = [b]
count = 1
while (not all_equal(temp_a, a) or not all_equal(temp_b, b)) and len(temp_a) and len(temp_b):
	a.append(temp_a)
	b.append(temp_b)
	a1 = temp_a[1:]
	b1 = temp_b[1:]
	if temp_a[0] > temp_b[0]:
		a1.append(temp_b[0])
		a1.append(temp_a[0])
	else:
		b1.append(temp_a[0])
		b1.append(temp_b[0])
	temp_a = a1
	temp_b = b1
	count += 1
if not len(temp_a):
	print(count, 2)
elif not len(temp_b):
	print(count, 1)
else:
	print(-1)


from collections import deque
n = int(input())
dec1 = deque()
dec2 = deque()
k1 = input().split()
for i in range(1, len(k1)):
	dec1.append(int(k1[i]))
k2 = input().split()
for i in range(1, len(k2)):
	dec2.append(int(k2[i]))
isAnswer = False
for i in range(1, 1000):
	if len(dec1) == 0:
		print(str(i - 1) + ' ' + '2')
		isAnswer = True
		break
	elif len(dec2) == 0:
		print(str(i - 1) + ' ' + '1')
		isAnswer = True
		break
	x = dec1.popleft()
	y = dec2.popleft()
	if x > y:
		dec1.append(y)
		dec1.append(x)
	else:
		dec2.append(x)
		dec2.append(y)
if isAnswer == False:
	print(-1)


n = int(input())
stack1 = list(map(int, input().split()))
stack2 = list(map(int, input().split()))
k1 = stack1.pop(0)
k2 = stack2.pop(0)
final = 0
state = [(stack1[:], stack2[:])]
bool1 = True
while True:
	if (stack1, stack2) in state[:-1]:
		print(-1)
		bool1 = False
		break
	if stack1[0] > stack2[0]:
		stack1.append(stack2[0])
		stack2.pop(0)
		stack1.append(stack1[0])
		stack1.pop(0)
		state.append((stack1[:], stack2[:]))
	elif stack1[0] < stack2[0]:
		stack2.append(stack1[0])
		stack1.pop(0)
		stack2.append(stack2[0])
		stack2.pop(0)
		state.append((stack1[:], stack2[:]))
	if len(stack1) == 0:
		final = 2
		break
	elif len(stack2) == 0:
		final = 1
		break
if bool1:
	print(len(state) - 1)
	print(final)


from sys import stdin, stdout
cin = stdin.readline
cout = stdout.write
n = int(cin())
a = list(map(int, cin().split()))[1:]
b = list(map(int, cin().split()))[1:]
va = []
vb = []
count = 0
while True:
	if not a or not b:
		cout(str(count) + ' ' + str((not a) * 2 + (not b) * 1))
		break
	if b in vb and a in va:
		cout('-1')
		exit(0)
	va.append(a[:])
	vb.append(b[:])
	if a[0] > b[0]:
		a.append(b[0])
		a.append(a[0])
	else:
		b.append(a[0])
		b.append(b[0])
	a.pop(0)
	b.pop(0)
	count += 1


from collections import deque
input()
cards1 = deque(list(map(int, input().split()))[1:])
cards2 = deque(list(map(int, input().split()))[1:])
for i in range(1, 106):
	(card1, card2) = (cards1.popleft(), cards2.popleft())
	if card1 > card2:
		cards1.extend([card2, card1])
	else:
		cards2.extend([card1, card2])
	if not cards1:
		print(i, 2)
		break
	if not cards2:
		print(i, 1)
		break
else:
	print(-1)


import sys
import string
import math
from collections import defaultdict
from functools import lru_cache
from collections import Counter
from collections import deque
from fractions import Fraction

def mi(s):
	return map(int, s.strip().split())

def lmi(s):
	return list(mi(s))

def tmi(s):
	return tuple(mi(s))

def mf(f, s):
	return map(f, s)

def lmf(f, s):
	return list(mf(f, s))

def js(lst):
	return ' '.join((str(d) for d in lst))

def jsns(lst):
	return ''.join((str(d) for d in lst))

def line():
	return sys.stdin.readline().strip()

def linesp():
	return line().split()

def iline():
	return int(line())

def mat(n):
	matr = []
	for _ in range(n):
		matr.append(linesp())
	return matr

def matns(n):
	mat = []
	for _ in range(n):
		mat.append([c for c in line()])
	return mat

def mati(n):
	mat = []
	for _ in range(n):
		mat.append(lmi(line()))
	return mat

def pmat(mat):
	for row in mat:
		print(js(row))

def main():
	line()
	s = deque(lmi(line())[1:])
	t = deque(lmi(line())[1:])
	visited = set()
	fights = 0
	winner = None
	while True:
		if s and t:
			fights += 1
			if s[0] > t[0]:
				a = s.popleft()
				b = t.popleft()
				s.append(b)
				s.append(a)
			else:
				a = s.popleft()
				b = t.popleft()
				t.append(a)
				t.append(b)
			state = (str(s), str(t))
			if state in visited:
				print(-1)
				return
			else:
				visited.add(state)
		elif not s:
			winner = 2
			break
		elif not t:
			winner = 1
			break
	print(fights, winner)
main()


n = int(input())
l = list(map(int, input().split()))
l1 = list(map(int, input().split()))

def fact(k):
	p = 1
	for i in range(1, k + 1):
		p = p * i
	return p
ans = 0
ans1 = -1
z = fact(n + 1)
while True:
	if len(l) == 1 or (len(l1) == 1 or z < 0):
		break
	z -= 1
	ans += 1
	if l[1] > l1[1]:
		l.append(l1[1])
		l.append(l[1])
		l.remove(l[1])
		l1.remove(l1[1])
	else:
		l1.append(l[1])
		l1.append(l1[1])
		l.remove(l[1])
		l1.remove(l1[1])
	if len(l) == 1:
		ans1 = 2
	elif len(l1) == 1:
		ans1 = 1
if ans1 == -1:
	print(-1)
else:
	print(ans, end=' ')
	print(ans1)


from collections import deque
n = int(input())
inp = list(map(int, input().split(' ')))
first = deque()
for el in inp[1:]:
	first.append(el)
inp = list(map(int, input().split(' ')))
second = deque()
for el in inp[1:]:
	second.append(el)
end = False
res = ''
for i in range(1, 250000):
	tmp1 = first.popleft()
	tmp2 = second.popleft()
	if tmp1 > tmp2:
		first.append(tmp2)
		first.append(tmp1)
	else:
		second.append(tmp1)
		second.append(tmp2)
	if len(first) == 0:
		end = True
		res = str(i) + ' 2'
		break
	elif len(second) == 0:
		end = True
		res = str(i) + ' 1'
		break
print(-1 if not end else res)


def solve(a, b):
	state = set()
	count = 0
	while len(a) > 0 and len(b) > 0:
		k = str(a) + str(b)
		if k in state:
			return -1
		state.add(k)
		(x, y) = (a.pop(0), b.pop(0))
		if x > y:
			a.extend([y, x])
		else:
			b.extend([x, y])
		count += 1
	return (count, 1 if len(b) == 0 else 2)
f = lambda : list(map(int, input().split()))
input()
res = solve(f()[1:], f()[1:])
print(-1 if res == -1 else '{} {}'.format(res[0], res[1]))


n = int(input())
s = [[], []]
data = list(map(int, input().split()))
(k1, s[0]) = (data[0], [data[i + 1] for i in range(len(data) - 1)])
data = list(map(int, input().split()))
(k2, s[1]) = (data[0], [data[i + 1] for i in range(len(data) - 1)])
(ans, iter) = (0, 0)
while True:
	if len(s[0]) == 0:
		print(iter, 2)
		exit()
	if len(s[1]) == 0:
		print(iter, 1)
		exit()
	if iter > 100000:
		print(-1)
		exit()
	(a, b) = (s[0][0], s[1][0])
	s[0].pop(0)
	s[1].pop(0)
	if a < b:
		s[1].append(a)
		s[1].append(b)
	else:
		s[0].append(b)
		s[0].append(a)
	iter += 1


n = int(input())
soldier_1 = list(map(int, input().split()))
soldier_1 = soldier_1[1:]
soldier_2 = list(map(int, input().split()))
soldier_2 = soldier_2[1:]
unfinished = True
counter = 0
checker = len(soldier_1) + len(soldier_2)
while unfinished:
	if soldier_1[0] > soldier_2[0]:
		soldier_1.append(soldier_2[0])
		soldier_1.append(soldier_1[0])
		soldier_2.remove(soldier_2[0])
		soldier_1.remove(soldier_1[0])
		counter += 1
	elif soldier_1[0] < soldier_2[0]:
		soldier_2.append(soldier_1[0])
		soldier_2.append(soldier_2[0])
		soldier_1.remove(soldier_1[0])
		soldier_2.remove(soldier_2[0])
		counter += 1
	if counter >= 200:
		print(-1)
		break
	if len(soldier_1) == checker:
		print(counter, 1)
		unfinished = False
	elif len(soldier_2) == checker:
		print(counter, 2)
		unfinished = False


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return [int(x) for x in sys.stdin.readline().split()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def main():
	n = I()
	a = LI()[1:]
	b = LI()[1:]
	for i in range(100000):
		if a[0] > b[0]:
			a = a[1:] + [b[0], a[0]]
			b = b[1:]
			if len(b) == 0:
				return '{} {}'.format(i + 1, 1)
		else:
			b = b[1:] + [a[0], b[0]]
			a = a[1:]
			if len(a) == 0:
				return '{} {}'.format(i + 1, 2)
	return -1
print(main())


n = int(input())
l1 = list(map(int, input().split()))
l1.pop(0)
l2 = list(map(int, input().split()))
l2.pop(0)
cnt = 0
while 1:
	if len(l1) == 0 or len(l2) == 0:
		break
	cnt -= -1
	if l2[0] > l1[0]:
		l2.append(l1[0])
		l2.append(l2[0])
	else:
		l1.append(l2[0])
		l1.append(l1[0])
	l1.pop(0)
	l2.pop(0)
	if cnt == 100000:
		break
if cnt == 100000:
	print(-1)
elif len(l1) == 0:
	print(cnt, 2)
else:
	print(cnt, 1)


n = int(input())
list_1 = input().split()
list_2 = input().split()
n1 = int(list_1.pop(0))
n2 = int(list_2.pop(0))
(listt_1, listt_2) = ([], [])
for i in range(n1):
	list_1[i] = int(list_1[i])
	listt_1.append(list_1[i])
for i in range(n2):
	list_2[i] = int(list_2[i])
	listt_2.append(int(list_2[i]))
(no, l1, l2) = (0, [], [])
while True:
	l1.append([])
	l2.append([])
	for i in range(len(listt_1)):
		l1[no].append(listt_1[i])
	for i in range(len(listt_2)):
		l2[no].append(listt_2[i])
	if listt_1[0] > listt_2[0]:
		j = listt_2.pop(0)
		i = listt_1.pop(0)
		listt_1.append(j)
		listt_1.append(i)
	else:
		j = listt_1.pop(0)
		i = listt_2.pop(0)
		listt_2.append(j)
		listt_2.append(i)
	no += 1
	if len(listt_1) == 0:
		print(no, '2')
		break
	if len(listt_2) == 0:
		print(no, '1')
		break
	if listt_1 in l1 and listt_2 in l2:
		print('-1')
		break


n = int(input())
from collections import deque
from copy import copy
a = deque([*map(int, input().split())][1:])
b = deque([*map(int, input().split())][1:])
ta = copy(a)
tb = copy(b)
rounds = 0
while len(a) and len(b):
	if a[0] > b[0]:
		a.append(b[0])
		b.popleft()
		a.append(a[0])
		a.popleft()
	else:
		b.append(a[0])
		a.popleft()
		b.append(b[0])
		b.popleft()
	rounds += 1
	if a == ta and b == tb or rounds > 1000000.0:
		print(-1)
		exit()
print(rounds, 1 if len(a) else 2)


n = int(input())
l = list(map(int, input().split()))
l.reverse()
l.pop(-1)
k = list(map(int, input().split()))
k.reverse()
k.pop(-1)
ans = 0
flag = 0
q = 1000
while q:
	q -= 1
	if len(l) == 0 or len(k) == 0:
		if len(l) == 0:
			flag = 2
		if len(k) == 0:
			flag = 1
		break
	ans += 1
	x = l[-1]
	l.pop(-1)
	y = k[-1]
	k.pop(-1)
	if x > y:
		l.insert(0, y)
		l.insert(0, x)
	else:
		k.insert(0, x)
		k.insert(0, y)
if q == 0:
	print(-1)
else:
	print(ans, flag)


from sys import stdin

def get_ints():
	return list(map(int, stdin.readline().strip().split()))
input()
a = get_ints()[1:]
b = get_ints()[1:]
fights = 0
can_win = True
seen = {}
while len(a) > 0 and len(b) > 0:
	if repr([a, b]) in seen:
		if seen[repr([a, b])] > 20:
			can_win = False
			break
		else:
			seen[repr([a, b])] += 1
	else:
		seen[repr([a, b])] = 1
	if a[0] > b[0]:
		t1 = a[0]
		t2 = b[0]
		a = a[1:]
		b = b[1:]
		a.append(t2)
		a.append(t1)
	elif a[0] < b[0]:
		t1 = a[0]
		t2 = b[0]
		a = a[1:]
		b = b[1:]
		b.append(t1)
		b.append(t2)
	fights += 1
if not can_win:
	print(-1)
	exit()
winner = 1 if len(b) == 0 else 2
print(fights, winner)


from collections import deque
from copy import deepcopy
n = int(input())
A = deque(list(map(int, input().split()))[1:])
B = deque(list(map(int, input().split()))[1:])
state = []
state.append((deepcopy(A), deepcopy(B)))
cnt = 0
while len(A) > 0 and len(B) > 0:
	if A[0] > B[0]:
		A.append(B.popleft())
		A.append(A.popleft())
	else:
		B.append(A.popleft())
		B.append(B.popleft())
	if (A, B) in state:
		print(-1)
		break
	state.append((deepcopy(A), deepcopy(B)))
	cnt += 1
else:
	print(cnt, 1 if len(B) == 0 else 2)


configs = set()
total = 0

def trans(d):
	return '#'.join(map(str, d))

def is_cycle(d1, d2):
	t1 = trans(d1)
	t2 = trans(d2)
	return t1 + '@' + t2 in configs or t2 + '@' + t1 in configs

def add_config(d1, d2):
	configs.add(trans(d1) + '@' + trans(d2))
	configs.add(trans(d2) + '@' + trans(d1))

def step(d1, d2):
	add_config(d1, d2)
	global total
	total += 1
	k1 = d1.pop(0)
	k2 = d2.pop(0)
	if k1 > k2:
		d1.append(k2)
		d1.append(k1)
	else:
		d2.append(k1)
		d2.append(k2)
	if len(d1) == 0:
		print(total, 2)
		exit(0)
	elif len(d2) == 0:
		print(total, 1)
		exit(0)
	elif is_cycle(d1, d2):
		print(-1)
		exit(0)
n = int(input())
d1 = list(map(int, input().split()))[1:]
d2 = list(map(int, input().split()))[1:]
while True:
	step(d1, d2)


n = int(input())
per1 = input().split()
per2 = input().split()
A = per1[1:]
B = per2[1:]

def func(A, B):
	if int(A[0]) > int(B[0]):
		A.append(B.pop(0))
		A.append(A.pop(0))
	else:
		B.append(A.pop(0))
		B.append(B.pop(0))
answer = 0
s = 1
vse = set()
lenny = 0
while A and B:
	vse.add(''.join(A) + ',' + ''.join(B))
	func(A, B)
	if len(vse) == answer:
		s = 0
		break
	answer += 1
print(str(answer) + ' ' + str(2 if len(A) == 0 else 1) if s == 1 else -1)


import collections
n = int(input())
k1ss = list(map(int, input().split()))
k2ss = list(map(int, input().split()))
k1s = collections.deque(k1ss[1:], 2 * n)
k2s = collections.deque(k2ss[1:], 2 * n)

def solve(n, k1s, k2s):
	fs = 0
	visited = set()
	visited.add(tuple(k1s) + (0,) + tuple(k2s))
	while k1s and k2s:
		key = fight(k1s, k2s)
		if key in visited:
			return (-1,)
		visited.add(key)
		fs += 1
	if k1s:
		return (fs, 1)
	else:
		return (fs, 2)

def fight(k1s, k2s):
	k1 = k1s.popleft()
	k2 = k2s.popleft()
	if k1 > k2:
		k1s.append(k2)
		k1s.append(k1)
	else:
		k2s.append(k1)
		k2s.append(k2)
	return tuple(k1s) + (0,) + tuple(k2s)
print(*solve(n, k1s, k2s))


from bisect import *
from math import *
from collections import *
from sys import stdin, stdout
input = stdin.readline
I = lambda : int(input())
M = lambda : map(int, input().split())
LI = lambda : list(map(int, input().split()))
for _ in range(1):
	I()
	a = LI()
	b = LI()
	a = deque(a[1:])
	b = deque(b[1:])
	c = deque() + a
	d = deque() + b
	flag = 1
	Pgames = 0
	d1 = [list(c)]
	d2 = [list(d)]
	while len(c) and len(d) and flag:
		t1 = c[0]
		t2 = d[0]
		if c[0] > d[0]:
			c.append(t2)
			c.append(t1)
		else:
			d.append(t1)
			d.append(t2)
		c.popleft()
		d.popleft()
		Pgames += 1
		if list(c) in d1 and list(d) in d2:
			flag = 0
		d1 += [list(c)]
		d2 += [list(d)]
	if not flag:
		print(-1)
	elif len(c) == 0:
		print(Pgames, 2)
	else:
		print(Pgames, 1)


import sys
n = int(input())
d1 = list(map(int, input().split(' ')))
d2 = list(map(int, input().split(' ')))
k1 = d1[0]
k2 = d2[0]
d1.remove(d1[0])
d2.remove(d2[0])
moves = 0
while True:
	if moves > 500000:
		print(-1)
		return
	a = d1[0]
	d1.remove(d1[0])
	b = d2[0]
	d2.remove(d2[0])
	if a > b:
		moves += 1
		d1.append(b)
		d1.append(a)
		if len(d2) == 0:
			print(str(moves) + ' 1')
			return
	if b > a:
		moves += 1
		d2.append(a)
		d2.append(b)
		if len(d1) == 0:
			print(str(moves) + ' 2')
			return


d = int(input())
d1 = list(map(int, input().split()))[1:]
d2 = list(map(int, input().split()))[1:]
f = 0
while d1 and d2:
	if f > 5000:
		print(-1)
		exit()
	if d1[0] > d2[0]:
		d1.append(d2[0])
		d1.append(d1[0])
		d1.pop(0)
		d2.pop(0)
	else:
		d2.append(d1[0])
		d2.append(d2[0])
		d1.pop(0)
		d2.pop(0)
	f += 1
if d1:
	print(f, 1)
else:
	print(f, 2)


ii = lambda : int(input())
kk = lambda : map(int, input().split())
ll = lambda : list(kk())
vis = set()
n = ii()
ls = ll()[1:]
ls2 = ll()[1:]
c = 0
while ls and ls2:
	c += 1
	a = ls[0]
	b = ls2[0]
	ls = ls[1:]
	ls2 = ls2[1:]
	if a > b:
		ls.extend([b, a])
	else:
		ls2.extend([a, b])
	tup = (tuple(ls), tuple(ls2))
	if tup in vis:
		print(-1)
		exit()
	vis.add(tup)
print(c, 1 if ls else 2)
exit()


n = int(input())
a = [int(x) for x in input().split()[1:]]
b = [int(x) for x in input().split()[1:]]
s = set()
t = 0
while len(a) * len(b):
	t += 1
	x = a.pop(0)
	y = b.pop(0)
	if x > y:
		a.append(y)
		a.append(x)
	else:
		b.append(x)
		b.append(y)
	k = (tuple(a), tuple(b))
	if k in s:
		print(-1)
		exit()
	s.add(k)
print(t, 1 if len(a) else 2)


n = int(input())
a = input().split()
k1 = int(a[0])
for i in range(k1 + 1):
	a[i] = int(a[i])
a.pop(0)
b = input().split()
k2 = int(b[0])
for i in range(k2 + 1):
	b[i] = int(b[i])
b.pop(0)
cnt = 0
while cnt <= 10000:
	if len(b) == 0:
		print(cnt, 1)
		exit()
	if len(a) == 0:
		print(cnt, 2)
		exit()
	if a[0] < b[0]:
		b.insert(len(b), a[0])
		b.insert(len(b), b[0])
		b.pop(0)
		a.pop(0)
	else:
		a.insert(len(a), b[0])
		a.insert(len(a), a[0])
		b.pop(0)
		a.pop(0)
	cnt += 1
print(-1)


import sys, os, io
from collections import deque
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
inp = [int(i) for i in input().split()]
k1 = inp[0]
a = inp[1:]
a = deque(a)
inp = [int(i) for i in input().split()]
k2 = inp[0]
b = inp[1:]
b = deque(b)
cnt = 0
while len(a) and len(b):
	cnt += 1
	if cnt == 10 ** 6:
		break
	if a[0] > b[0]:
		f = a.popleft()
		s = b.popleft()
		a.append(s)
		a.append(f)
	else:
		f = a.popleft()
		s = b.popleft()
		b.append(f)
		b.append(s)
if cnt == 10 ** 6:
	print(-1)
elif len(a) == 0:
	print(cnt, 2)
else:
	print(cnt, 1)


n = int(input())
arr = list(map(int, input().split()))
(n1, arr) = (arr[0], arr[1:])
brr = list(map(int, input().split()))
(n2, brr) = (brr[0], brr[1:])
mapper = {}
cnt = 0
can = True
while arr != [] and brr != []:
	(s, t) = (tuple(arr), tuple(brr))
	if s in mapper and mapper[s] == t:
		can = False
		break
	else:
		mapper[s] = t
	x = arr[0]
	arr.pop(0)
	y = brr[0]
	brr.pop(0)
	if y > x:
		brr.append(x)
		brr.append(y)
	else:
		arr.append(y)
		arr.append(x)
	cnt += 1
if can == False:
	print(-1)
elif len(arr) == 0:
	print(cnt, 2)
else:
	print(cnt, 1)


import math
n = int(input())
p1 = list(map(int, input().split()))
p2 = list(map(int, input().split()))
p1.pop(0)
p2.pop(0)
totTurns = math.factorial(n + 1)
prevCard = 0
for i in range(totTurns):
	(a, b) = (p1.pop(0), p2.pop(0))
	if a > b:
		p1.extend([b, a])
	else:
		p2.extend([a, b])
	if not p1 or not p2:
		print(i + 1, 1 if p1 else 2)
		break
else:
	print(-1)


n = int(input())
as_ = list(map(int, input().split(' ')))
bs_ = list(map(int, input().split(' ')))
as_ = as_[1:]
bs_ = bs_[1:]

def play_round():
	global as_, bs_
	a = as_[0]
	as_ = as_[1:]
	b = bs_[0]
	bs_ = bs_[1:]
	if a > b:
		as_.append(b)
		as_.append(a)
	else:
		bs_.append(a)
		bs_.append(b)
has_played = set()
n = 0
while True:
	if len(as_) == 0 or len(bs_) == 0:
		break
	s = ','.join(map(str, as_)) + ':' + ','.join(map(str, bs_))
	if s in has_played:
		break
	has_played.add(s)
	play_round()
	n += 1
if len(as_) == 0:
	print(n, 2)
elif len(bs_) == 0:
	print(n, 1)
else:
	print(-1)


n = int(input())
string = input()
s1 = list(map(int, string.split()))
string = input()
s2 = list(map(int, string.split()))
del s1[0], s2[0]
cards1 = []
cards2 = []
a = 0
while True:
	if len(s1) == 0:
		print(str(a) + ' 2')
		break
	elif len(s2) == 0:
		print(str(a) + ' 1')
		break
	x = s1[0]
	y = s2[0]
	del s1[0], s2[0]
	if x > y:
		s1.append(y)
		s1.append(x)
	else:
		s2.append(x)
		s2.append(y)
	condition = False
	for x in range(a):
		if cards1[x] == s1 and cards2[x] == s2:
			print(-1)
			condition = True
			break
	if condition:
		break
	cards1.append(s1[:])
	cards2.append(s2[:])
	a += 1


num_cards = int(input())
person1 = tuple(list(map(int, input().split()))[1:])
person2 = tuple(list(map(int, input().split()))[1:])
has_happened = set()
fights = 0
while (person1, person2) not in has_happened and person1 != () and (person2 != ()) and ((person2, person1) not in has_happened):
	has_happened.add((person1, person2))
	c1 = person1[0]
	c2 = person2[0]
	if c1 > c2:
		person1 = person1[1:] + (c2, c1)
		person2 = person2[1:]
	else:
		person2 = person2[1:] + (c1, c2)
		person1 = person1[1:]
	fights += 1
if (person1, person2) in has_happened or (person2, person1) in has_happened:
	print(-1)
elif person1 == ():
	print(fights, 2)
else:
	print(fights, 1)


n = int(input())
x1 = list(map(int, input().strip().split()))
x2 = list(map(int, input().strip().split()))
n1 = x1[0]
n2 = x2[0]
x1 = x1[1:]
x2 = x2[1:]
counter = 0
won = False
while True:
	if len(x1) == 0:
		print(str(counter) + ' ' + str(2))
		break
	if len(x2) == 0:
		print(str(counter) + ' ' + str(1))
		break
	if counter >= 100000:
		print(-1)
		break
	if x1[0] > x2[0]:
		x1.append(x2[0])
		x1.append(x1[0])
		x1 = x1[1:]
		x2 = x2[1:]
	else:
		x2.append(x1[0])
		x2.append(x2[0])
		x2 = x2[1:]
		x1 = x1[1:]
	counter += 1


from collections import deque
from sys import stdin
tot = int(stdin.readline())
arr1 = deque(list(map(int, stdin.readline().split()))[1:][::-1])
arr2 = deque(list(map(int, stdin.readline().split()))[1:][::-1])
seen = list()
cnt = 0
while True:
	if ''.join(list(map(str, arr1))) + ''.join(list(map(str, arr2))) in seen:
		print(-1)
		break
	seen.append(''.join(list(map(str, arr1))) + ''.join(list(map(str, arr2))))
	el_arr1 = arr1.pop()
	el_arr2 = arr2.pop()
	if el_arr1 > el_arr2:
		arr1.appendleft(el_arr2)
		arr1.appendleft(el_arr1)
	else:
		arr2.appendleft(el_arr1)
		arr2.appendleft(el_arr2)
	cnt += 1
	if len(arr1) == 0:
		print(cnt, '2')
		break
	if len(arr2) == 0:
		print(cnt, '1')
		break


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = a[1:]
b = b[1:]
count = 0
flag = False
while len(a) != 0 and len(b) != 0:
	x = a.pop(0)
	y = b.pop(0)
	if x < y:
		b.append(x)
		b.append(y)
	elif x > y:
		a.append(y)
		a.append(x)
	count += 1
	if count == 50000:
		flag = True
		break
if flag:
	print(-1)
elif len(a) > len(b):
	print(count, 1)
elif len(b) > len(a):
	print(count, 2)


input()
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
count = 0
while a and b:
	c = a.pop(0)
	d = b.pop(0)
	if c > d:
		a += [d, c]
	else:
		b += [c, d]
	count += 1
	if count > 1000:
		print(-1)
		break
else:
	print(count, [1, 2][len(a) == 0])


from collections import Counter
import string
import math
import sys

def array_int():
	return [int(i) for i in sys.stdin.readline().split()]

def vary(arrber_of_variables):
	if arrber_of_variables == 1:
		return int(sys.stdin.readline())
	if arrber_of_variables >= 2:
		return map(int, sys.stdin.readline().split())

def makedict(var):
	return dict(Counter(var))

def printDivisors(n):
	divisors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				divisors.append(i)
			else:
				divisors.extend((i, n // i))
		i = i + 1
	return divisors
n = vary(1)
num1 = array_int()
fn = num1[0]
fcn = num1[1:]
num1 = array_int()
sn = num1[0]
scn = num1[1:]
count = 0
i = 10 ** 5
while i:
	if len(fcn) == 0:
		print(count, 2)
		break
	if len(scn) == 0:
		print(count, 1)
		break
	if fcn[0] > scn[0]:
		fcn.extend((scn[0], fcn[0]))
		fcn.pop(0)
		scn.pop(0)
		count += 1
	elif scn[0] > fcn[0]:
		scn.extend((fcn[0], scn[0]))
		scn.pop(0)
		fcn.pop(0)
		count += 1
	i -= 1
else:
	print(-1)


def to_list(s):
	return list(map(lambda x: int(x), s.split(' ')))

def make_step(a, b):
	(a_copy, b_copy) = (a.copy(), b.copy())
	if a_copy[0] > b_copy[0]:
		a_copy.extend([b_copy[0], a[0]])
	else:
		b_copy.extend([a_copy[0], b_copy[0]])
	(a_copy, b_copy) = (a_copy[1:], b_copy[1:])
	return (a_copy, b_copy)

def solve(a, b):
	k = 0
	arrays = [(a, b)]
	while True:
		(a, b) = make_step(a, b)
		k += 1
		if (a == []) | (b == []):
			break
		if (a, b) in arrays:
			return -1
		arrays.append((a, b))
	if a == []:
		number = 2
	else:
		number = 1
	return str(k) + ' ' + str(number)
n = int(input())
a = to_list(input())[1:]
b = to_list(input())[1:]
print(solve(a, b))


n = int(input())
(a1, a2) = ([], [])
ins = list(map(int, input().split()))
for i in range(1, ins[0] + 1):
	a1.append(ins[i])
ins = list(map(int, input().split()))
for i in range(1, ins[0] + 1):
	a2.append(ins[i])
kol = 0
while 89 == 89:
	kol += 1
	if kol > 10000:
		break
	if a1[0] > a2[0]:
		a1.append(a2[0])
		a1.append(a1[0])
		a1.pop(0)
		a2.pop(0)
	else:
		a2.append(a1[0])
		a2.append(a2[0])
		a1.pop(0)
		a2.pop(0)
	if not a1 or not a2:
		break
if not a1:
	print(kol, 2)
elif not a2:
	print(kol, 1)
else:
	print(-1)


from collections import deque
n = int(input())
inp = input()
k1 = int(inp[0])
p1 = [int(x) for x in inp.split()[1:]]
inp = input()
k2 = int(inp[0])
p2 = [int(x) for x in inp.split()[1:]]
player1 = deque(p1)
player2 = deque(p2)
winnable = False
counter = 0
while counter < 1000:
	try:
		card1 = player1.popleft()
		card2 = player2.popleft()
	except IndexError:
		winnable = True
		break
	if card1 > card2:
		player1.append(card2)
		player1.append(card1)
	else:
		player2.append(card1)
		player2.append(card2)
	counter += 1
if not winnable:
	print(-1)
else:
	try:
		player1.pop()
	except IndexError:
		print(f'{counter} 2')
	try:
		player2.pop()
	except IndexError:
		print(f'{counter} 1')


import math
from decimal import *
import random
n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
cnt = 0
fnd = False
ans = 0
while len(a) > 0 and len(b) > 0 and (cnt < int(100000.0)):
	if a[0] > b[0]:
		a += [b[0]] + [a[0]]
		a = a[1:]
		b = b[1:]
	else:
		b += [a[0]] + [b[0]]
		a = a[1:]
		b = b[1:]
	cnt += 1
	if len(a) == 0:
		ans = 2
		fnd = True
		break
	if len(b) == 0:
		ans = 1
		fnd = True
		break
if fnd:
	print(cnt, ans)
else:
	print(-1)


from itertools import chain

def main():
	input()
	aa = list(map(int, input().split()))[1:]
	bb = list(map(int, input().split()))[1:]
	(visited, cnt) = (set(), 0)
	while aa and bb:
		cnt += 1
		(a, b) = (aa.pop(0), bb.pop(0))
		if a > b:
			aa.append(b)
			aa.append(a)
		else:
			bb.append(a)
			bb.append(b)
		k = tuple(chain(aa, (0,), bb))
		if k in visited:
			print(-1)
			return
		else:
			visited.add(k)
	print(cnt, 1 + (not aa))
main()


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def array_equal(a, b):
	if len(a) == len(b):
		for i in range(len(a)):
			if a[i] == b[i]:
				continue
			else:
				return False
		return True
	else:
		return False
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
k1 = a[0]
k2 = b[0]
a.pop(0)
b.pop(0)
a_hat = a.copy()
b_hat = b.copy()
c = 0
while True:
	if a[0] > b[0]:
		a.append(b.pop(0))
		a.append(a.pop(0))
		c += 1
	else:
		b.append(a.pop(0))
		b.append(b.pop(0))
		c += 1
	if len(a) == 0:
		print(str(c) + ' 2')
		break
	if len(b) == 0:
		print(str(c) + ' 1')
		break
	if array_equal(a, a_hat) and array_equal(b, b_hat) or c > 1000:
		print(-1)
		break


import sys
import math
import queue

def worker():
	while True:
		item = q.get()
		do_work(item)
		q.task_done()
N = int(input())
a1 = input().split()
n1 = int(a1[0])
q1 = queue.Queue()
for x in a1[1:]:
	q1.put(int(x))
a1 = input().split()
n2 = int(a1[0])
q2 = queue.Queue()
for x in a1[1:]:
	q2.put(int(x))
cou = 0
while cou <= 200:
	cou += 1
	a = q1.get()
	b = q2.get()
	if a > b:
		q1.put(b)
		q1.put(a)
	else:
		q2.put(a)
		q2.put(b)
	if q1.empty():
		print(cou, '2')
		break
	if q2.empty():
		print(cou, '1')
		break
else:
	print('-1')


n = int(input())
k1 = list(map(int, input().split()))[1:]
k2 = list(map(int, input().split()))[1:]
state = dict()
counter = 0
while k1 and k2:
	counter += 1
	if counter >= 10000:
		break
	(x, y) = (k1.pop(0), k2.pop(0))
	if x > y:
		k1 += [y, x]
	else:
		k2 += [x, y]
if counter == 10000:
	print(-1)
else:
	print(counter, 1 if k1 else 2)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest
sys.setrecursionlimit(111111)
INF = 99999999999999999999999999999999

def main():
	mod = 1000000007
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = 1
	for _ in range(tc):
		n = ri()
		pl1 = ria()
		pl2 = ria()
		(n1, p1) = (pl1[0], deque(pl1[1:][::-1]))
		(n2, p2) = (pl2[0], deque(pl2[1:][::-1]))
		d = {}
		whowon = 0
		fights = 0
		d[tuple(p1), tuple(p2)] = 1
		while len(p1) and len(p2):
			if p1[-1] > p2[-1]:
				p1.appendleft(p2.pop())
				p1.appendleft(p1.pop())
			else:
				p2.appendleft(p1.pop())
				p2.appendleft(p2.pop())
			if (tuple(p1), tuple(p2)) not in d:
				d[tuple(p1), tuple(p2)] = 1
			else:
				whowon = -1
				break
			fights += 1
		if whowon == -1:
			print(-1)
		elif len(p1):
			print(fights, 1)
		else:
			print(fights, 2)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


from collections import deque
n = int(input())
t = [int(i) for i in input().split()]
c1 = deque(t[1:])
t = [int(i) for i in input().split()]
c2 = deque(t[1:])
f = 0
while len(c1) > 0 and len(c2) > 0 and (f < 10 ** 6):
	f += 1
	d1 = c1.popleft()
	d2 = c2.popleft()
	if d1 > d2:
		c1.extend([d2, d1])
	else:
		c2.extend([d1, d2])
if f == 10 ** 6:
	print(-1)
elif len(c1) != 0:
	print(f, 1)
else:
	print(f, 2)


from sys import stdin, stdout
input = stdin.readline

def write(n, sep='\n'):
	stdout.write(str(n))
	stdout.write(sep)

def gil():
	return list(map(int, input().split()))
n = int(input())
(a, *ka) = gil()
(b, *kb) = gil()
s = []
c = 0
while len(ka) > 0 and len(kb) > 0:
	c += 1
	x = (ka.copy(), kb.copy())
	if x in s:
		print(-1)
		break
	s.append(x)
	a = ka.pop(0)
	b = kb.pop(0)
	if a > b:
		ka.append(b)
		ka.append(a)
	else:
		kb.append(a)
		kb.append(b)
else:
	if len(ka) == 0:
		y = 2
	else:
		y = 1
	print(c, y)


from collections import deque
n = input()
a = deque(list(map(int, input().split()))[1:])
b = deque(list(map(int, input().split()))[1:])
it = 0
while a and b:
	x = a.popleft()
	y = b.popleft()
	if x > y:
		a.append(y)
		a.append(x)
	else:
		b.append(x)
		b.append(y)
	it += 1
	if it >= 999999:
		break
if not a:
	print(it, 2)
elif not b:
	print(it, 1)
else:
	print(-1)


import os
import sys
from io import BytesIO, IOBase
mod = 10 ** 9 + 7
from collections import deque

def main():
	n = int(input())
	one = deque(map(int, input().split()))
	two = deque(map(int, input().split()))
	one.popleft()
	two.popleft()
	c = one.copy()
	d = two.copy()
	ans = 0
	win = 0
	while True:
		if ans > 100000:
			win = 0
			break
		ans += 1
		if one[0] > two[0]:
			temp = two.popleft()
			temp2 = one.popleft()
			one.append(temp)
			one.append(temp2)
		else:
			temp = one.popleft()
			temp2 = two.popleft()
			two.append(temp)
			two.append(temp2)
		if len(one) == 0:
			win = 2
			break
		elif len(two) == 0:
			win = 1
			break
		elif one[0] == c[0] and two[0] == d[0]:
			if one == c and two == d:
				win = 0
				break
	if win:
		print(ans, win)
	else:
		print(-1)

def nouse0():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse1():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse2():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def nouse3():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse4():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse5():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')
main()


import sys
from datetime import datetime
n = int(input())
k1 = input().split()
k2 = input().split()
k1 = [int(x) for x in k1]
k2 = [int(x) for x in k2]
k1.pop(0)
k2.pop(0)
iteration = 0
while len(k1) != 0 and len(k2) != 0:
	karta_1 = k1[0]
	karta_2 = k2[0]
	if karta_2 > karta_1:
		k1.pop(0)
		k2.pop(0)
		k2.append(karta_1)
		k2.append(karta_2)
	if karta_2 < karta_1:
		k2.pop(0)
		k1.pop(0)
		k1.append(karta_2)
		k1.append(karta_1)
	iteration = iteration + 1
	if iteration > 150:
		break
if iteration > 150:
	print(-1)
	sys.exit()
if len(k2) != 0:
	print(iteration, 2)
if len(k1) != 0:
	print(iteration, 1)


import math
import random
from queue import Queue

def main(arr1, arr2):
	q1 = Queue(maxsize=0)
	q2 = Queue(maxsize=0)
	seen = set([])
	ans = 0
	while len(arr1) != 0 and len(arr2) != 0:
		e = (tuple(arr1), tuple(arr2))
		if e not in seen:
			seen.add(e)
		else:
			print(-1)
			return
		val1 = arr1.pop(0)
		val2 = arr2.pop(0)
		if val1 > val2:
			arr1.append(val2)
			arr1.append(val1)
		else:
			arr2.append(val1)
			arr2.append(val2)
		ans += 1
	if len(arr1) == 0:
		print(ans, 2)
	else:
		print(ans, 1)
	return
n = int(input())
arr1 = list(map(int, input().split()))[1:]
arr2 = list(map(int, input().split()))[1:]
main(arr1, arr2)


from collections import deque
n = int(input())
list1 = list(input().split())
list2 = list(input().split())
k1 = int(list1[0])
k2 = int(list2[0])
q1 = deque()
q2 = deque()
for i in range(1, k1 + 1):
	q1.append(list1[i])
for i in range(1, k2 + 1):
	q2.append(list2[i])
fights = 0
seen = set()
seen.add((''.join(q1), ''.join(q2)))
never_end = False
while len(q1) and len(q2):
	fights += 1
	a = q1.popleft()
	b = q2.popleft()
	if (''.join(q1), ''.join(q2)) in seen:
		never_end = True
		break
	else:
		seen.add((''.join(q1), ''.join(q2)))
	if int(a) > int(b):
		q1.append(b)
		q1.append(a)
	else:
		q2.append(a)
		q2.append(b)
if never_end:
	print(-1)
elif len(q1):
	print(fights, 1)
else:
	print(fights, 2)


class Queue(object):

	def __init__(self):
		self.items = []

	def enque(self, new):
		self.items.append(new)

	def deque(self):
		return self.items.pop(0)

	def peek(self):
		return self.items[0]

	def isempty(self):
		return self.items == []

	def size(self):
		return len(self.iems)

	def __eq__(self, other):
		return self.items == other.items
n = int(input())
L1 = [int(s) for s in input().split()]
L2 = [int(s) for s in input().split()]
(Q1, Q2) = (Queue(), Queue())
for i in range(1, len(L1)):
	Q1.enque(L1[i])
for i in range(1, len(L2)):
	Q2.enque(L2[i])
c = 0
while not Q1.isempty() and (not Q2.isempty()) and (c <= 2 ** n):
	(r1, r2) = (Q1.deque(), Q2.deque())
	if r1 > r2:
		Q1.enque(r2)
		Q1.enque(r1)
	else:
		Q2.enque(r1)
		Q2.enque(r2)
	c += 1
if Q1.isempty():
	print(' '.join([str(c), '2']))
elif Q2.isempty():
	print(' '.join([str(c), '1']))
else:
	print(-1)


n = int(input())
a = tuple(map(int, input().split()))[1:]
b = tuple(map(int, input().split()))[1:]
c = 0
s = set()
res = 0
while (a, b) not in s:
	if not a:
		res = 2
		break
	if not b:
		res = 1
		break
	s.add((a, b))
	(x, y) = (a[0], b[0])
	(a, b) = (a[1:], b[1:])
	c += 1
	if x < y:
		b = b + (x, y)
	else:
		a = a + (y, x)
if res == 0:
	print(-1)
else:
	print(c, res)


for t in range(1):
	n = int(input())
	row1 = list(map(int, input().split()))
	row2 = list(map(int, input().split()))
	row1 = row1[1:]
	row2 = row2[1:]
	broken = 0
	for i in range(1, 10 ** 4):
		ele1 = row1.pop(0)
		ele2 = row2.pop(0)
		if ele1 > ele2:
			row1.append(ele2)
			row1.append(ele1)
		else:
			row2.append(ele1)
			row2.append(ele2)
		if len(row1) == 0:
			print(i, 2)
			broken += 1
			break
		elif len(row2) == 0:
			print(i, 1)
			broken += 1
			break
		else:
			continue
	if broken == 0:
		print(-1)


N = int(input())
from collections import deque
A = deque()
B = deque()
for x in range(2):
	a = input().split()
	if x == 0:
		for y in range(1, len(a)):
			A.append(int(a[y]))
	else:
		for y in range(1, len(a)):
			B.append(int(a[y]))
br = 0
p = 0
while len(A) != 0 and len(B) != 0 and (br < 300000):
	c = A.popleft()
	d = B.popleft()
	if c > d:
		A.append(d)
		A.append(c)
		p = 1
	else:
		B.append(c)
		B.append(d)
		p = 2
	br += 1
if br >= 300000:
	print(-1)
else:
	print(br, p)


n = int(input())
p1 = input().strip().split()
p1 = [int(i) for i in p1[1:]]
p2 = input().strip().split()
p2 = [int(i) for i in p2[1:]]
comb = set()
cont = 0
while True:
	if tuple(p1 + [0] + p2) in comb:
		print(-1)
		break
	if len(p1) == 0:
		print(cont, 2)
		break
	if len(p2) == 0:
		print(cont, 1)
		break
	cont += 1
	comb.add(tuple(p1 + [0] + p2))
	p1_card = p1.pop(0)
	p2_card = p2.pop(0)
	if p2_card < p1_card:
		p1 += [p2_card, p1_card]
	else:
		p2 += [p1_card, p2_card]


from math import factorial
n = int(input())
s1 = [int(i) for i in input().split()][1:]
s2 = [int(i) for i in input().split()][1:]
(i, finished, N) = (1, False, 120)
while s1 and s2:
	(x, y) = (s1.pop(0), s2.pop(0))
	if x > y:
		s1 += [y, x]
	else:
		s2 += [x, y]
	if i == N:
		print(-1)
		break
	i = i + 1
if not s1:
	print(i - 1, 2)
elif not s2:
	print(i - 1, 1)


from collections import Counter, defaultdict, deque
from math import factorial as fact
t = int(input())

def sim(a1, a2):
	if a1[0] > a2[0]:
		a = a2.pop(0)
		b = a1.pop(0)
		a1.extend([a, b])
	else:
		a = a1.pop(0)
		b = a2.pop(0)
		a2.extend([a, b])
visited = set()
c = 0
s1 = [int(x) for x in input().split()]
s2 = [int(x) for x in input().split()]
s1.pop(0)
s2.pop(0)
while True:
	if len(s1) == 0 or len(s2) == 0:
		break
	h = hash(str([s1, s2]))
	if h in visited:
		print(-1)
		exit()
	visited.add(h)
	sim(s1, s2)
	c += 1
if len(s1) == 0:
	print(c, 2)
else:
	print(c, 1)


n = int(input())
a = list(map(int, input().split()))
k1 = a[0]
s1 = a[1:]
a = list(map(int, input().split()))
k2 = a[0]
s2 = a[1:]
flag = 0
fights = 0
count = 0
while len(s1) != 0 and len(s2) != 0:
	count += 1
	if count > 1000000:
		flag = 1
		break
	t = s1.pop(0)
	p = s2.pop(0)
	if t > p:
		s1.append(p)
		s1.append(t)
	else:
		s2.append(t)
		s2.append(p)
	fights += 1
if flag == 1:
	print('-1')
else:
	if len(s1) == 0:
		won = '2'
	else:
		won = '1'
	print(fights, won, sep=' ')


n = int(input())

def inp(s):
	j = 0
	a = []
	for i in range(len(s)):
		if s[i] == ' ':
			a.append(int(s[j:i]))
			j = i + 1
		if i == len(s) - 1:
			a.append(int(s[j:]))
	return a
s1 = input()
s2 = input()
a = inp(s1)
b = inp(s2)
a = a[1:]
b = b[1:]
p = [a]
q = [b]
i = 0
while len(a) != 0 and len(b) != 0:
	if a[0] > b[0]:
		x = a[0]
		y = b[0]
		a = a[1:]
		b = b[1:]
		a.append(y)
		a.append(x)
	else:
		x = a[0]
		y = b[0]
		a = a[1:]
		b = b[1:]
		b.append(x)
		b.append(y)
	i = i + 1
	if a in p and b in q:
		i = -1
		break
	p.append(a)
	q.append(b)
print(str(i) + ' ', end='')
if len(a) == 0:
	print(2)
elif len(b) == 0:
	print(1)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
n = ii1()
(_, *a) = iia()
(_, *b) = iia()
if len(b) == 0:
	print(0, 1)
else:
	(old_a, old_b) = (set(), set())
	res = 0
	while True:
		old_a.add(tuple(a))
		old_b.add(tuple(b))
		cur_a = a.pop(0)
		cur_b = b.pop(0)
		res += 1
		if cur_a > cur_b:
			a.extend([cur_b, cur_a])
		else:
			b.extend([cur_a, cur_b])
		if not len(a):
			print(res, 2)
			break
		if not len(b):
			print(res, 1)
			break
		if tuple(a) in old_a and tuple(b) in old_b:
			print(-1)
			break


n = input()
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
r = 0
while a and b:
	r += 1
	if r > 1000:
		print(-1)
		exit(0)
	(x, y) = (a.pop(0), b.pop(0))
	if x > y:
		a += [y, x]
	else:
		b += [x, y]
if a:
	print(r, 1)
else:
	print(r, 2)


n = int(input())
s1 = list(map(int, input().split()))[1:]
s2 = list(map(int, input().split()))[1:]
c = 0
while s1 and s2 and (c < 10 ** 5):
	if s1[0] > s2[0]:
		s1.append(s2[0])
		s1.append(s1[0])
	else:
		s2.append(s1[0])
		s2.append(s2[0])
	s1.pop(0)
	s2.pop(0)
	c += 1
if not s1:
	print(c, 2)
elif not s2:
	print(c, 1)
else:
	print(-1)


import queue
n = int(input())
x = [int(j) for j in input().split()]
y = [int(j) for j in input().split()]
k1 = x[0]
k2 = y[0]
a = x[1:]
b = y[1:]
s = ()
c = 0
q1 = queue.Queue()
q2 = queue.Queue()
for i in range(k1):
	q1.put(a[i])
for i in range(k2):
	q2.put(b[i])
while q1.empty() != True and q2.empty() != True:
	c1 = q1.get()
	c2 = q2.get()
	if c1 > c2:
		q1.put(c2)
		q1.put(c1)
	else:
		q2.put(c1)
		q2.put(c2)
	c += 1
	if c > 400:
		print(-1)
		exit(0)
		break
if q1.empty():
	k = 2
else:
	k = 1
print(c, k)


def helper(s1, s2, visited, move):
	(n, m) = (len(s1), len(s2))
	if n == 0:
		print(move, '2')
		return
	if m == 0:
		print(move, '1')
		return
	if tuple([tuple(s1), tuple(s2)]) in visited:
		print('-1')
		return
	else:
		visited.add(tuple([tuple(s1), tuple(s2)]))
	if s1[0] > s2[0]:
		a = s2.pop(0)
		s1 += [a, s1[0]]
		s1.pop(0)
	else:
		a = s1.pop(0)
		s2 += [a, s2[0]]
		s2.pop(0)
	helper(s1, s2, visited, move + 1)
n = [int(x) for x in input().split()]
a1 = [int(x) for x in input().split()]
a2 = [int(x) for x in input().split()]
visited = set()
helper(a1[1:], a2[1:], visited, 0)


cards = int(input())
start_first = input().split()[1:]
start_second = input().split()[1:]
hist = []
f = [c for c in start_first]
s = [c for c in start_second]
rounds = 0
while f and s:
	(c_f, c_s) = (f.pop(0), s.pop(0))
	if int(c_f) > int(c_s):
		f.append(c_s)
		f.append(c_f)
	else:
		s.append(c_f)
		s.append(c_s)
	rounds += 1
	if (f, s) in hist:
		print(-1)
		break
	hist.append(([x for x in f], [x for x in s]))
else:
	print(rounds, (1, 2)[f == []])


from sys import exit
n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
used = set()
cnt = 0
while len(a) != 0 and len(b) != 0:
	if (tuple(a), tuple(b)) not in used:
		used.add((tuple(a), tuple(b)))
	else:
		print(-1)
		exit(0)
	(x, y) = (a.pop(0), b.pop(0))
	if x > y:
		a.append(y)
		a.append(x)
	else:
		b.append(x)
		b.append(y)
	cnt += 1
print(cnt, '1' if len(b) == 0 else '2')


def getHash(a, b):
	if len(a) == 0 or len(b) == 0:
		return 0
	h = len(a)
	for i in range(len(a)):
		h = h * 10 + a[i]
	for i in range(len(b)):
		h = h * 10 + b[i]
	return h

def update(a, b):
	if a[0] > b[0]:
		a.append(b[0])
		a.append(a[0])
		a.pop(0)
		b.pop(0)
	elif a[0] < b[0]:
		b.append(a[0])
		b.append(b[0])
		a.pop(0)
		b.pop(0)

def main():
	n = int(input())
	a = list(map(int, input().split(' ')))
	a = a[1:len(a)]
	b = list(map(int, input().split(' ')))
	b = b[1:len(b)]
	cnt = 1
	for i in range(n, 1, -1):
		cnt *= i
	state = set()
	for i in range(cnt):
		update(a, b)
		h = int(getHash(a, b))
		if h == 0:
			print(i + 1, (len(a) == 0) + 1)
			break
		if h in state:
			print(-1)
			break
		else:
			state.add(h)
main()


n = int(input())
p1 = list(map(int, input().split()))
p2 = list(map(int, input().split()))
p1_cards = p1.pop(0)
p2_cards = p2.pop(0)
visited1 = []
visited2 = []
winner = -1
visited1.append(list(p1))
visited2.append(list(p2))
fights = 0
while True:
	if len(p1) == 0:
		winner = 2
		print(str(fights) + '  ' + str(winner))
		break
	if len(p2) == 0:
		winner = 1
		print(str(fights) + '  ' + str(winner))
		break
	if p1[0] >= p2[0]:
		p1.append(p2.pop(0))
		p1.append(p1.pop(0))
	else:
		p2.append(p1.pop(0))
		p2.append(p2.pop(0))
	if p1 in visited1 and p2 in visited2 or (p2 in visited1 and p1 in visited2):
		print(winner)
		break
	visited1.append(list(p1))
	visited2.append(list(p2))
	fights += 1


N = input()
list1 = [int(x) for x in input().split()]
list2 = [int(x) for x in input().split()]
list1.pop(0)
list2.pop(0)
s1 = tuple(map(int, list1))
s2 = tuple(map(int, list2))
already_seen = []
num_fights = 0
while len(list1) > 0 and len(list2) > 0:
	num_fights += 1
	if (s1, s2) in already_seen:
		break
	else:
		already_seen.append((s1, s2))
	if list1[0] < list2[0]:
		list2.append(list1[0])
		list2.append(list2[0])
		list2.pop(0)
		list1.pop(0)
	else:
		list1.append(list2[0])
		list1.append(list1[0])
		list2.pop(0)
		list1.pop(0)
	s1 = tuple(map(int, list1))
	s2 = tuple(map(int, list2))
if len(list1) == 0:
	print(str(num_fights) + ' 2')
elif len(list2) == 0:
	print(str(num_fights) + ' 1')
else:
	print(-1)


n = int(input())
a = [int(x) for x in input().split()]
a = a[1:]
b = [int(x) for x in input().split()]
b = b[1:]
k = 0
while len(a) > 0 and len(b) > 0 and (k <= 10 ** 3):
	if a[0] > b[0] and (not (a[0] == 0 and b[0] == 9) and (not (a[0] == 9 and b[0] == 0))):
		a.append(b[0])
		a.append(a[0])
		a.pop(0)
		b.pop(0)
		k += 1
	else:
		b.append(a[0])
		b.append(b[0])
		a.pop(0)
		b.pop(0)
		k += 1
if len(a) != 0 and len(b) != 0:
	print(-1)
elif len(a) > 0:
	print(k, 1)
else:
	print(k, 2)


n = int(input())
string1 = input()
string2 = input()
list1 = string1.split(' ')
list2 = string2.split(' ')
del list1[0]
del list2[0]
pile1 = []
pile2 = []
for i in range(len(list1)):
	pile1.append(int(list1[i]))
for i in range(len(list2)):
	pile2.append(int(list2[i]))
starting1 = pile1.copy()
starting2 = pile2.copy()
count = 0
while True:
	count += 1
	x = pile1[0]
	y = pile2[0]
	del pile1[0]
	del pile2[0]
	if x > y:
		pile1.append(y)
		pile1.append(x)
	if y > x:
		pile2.append(x)
		pile2.append(y)
	if len(pile1) == 0:
		print(str(count) + ' 2')
		break
	if len(pile2) == 0:
		print(str(count) + ' 1')
		break
	if pile1 == starting1 and pile2 == starting2:
		print('-1')
		break
	if count > 326592:
		print('-1')
		break


n = int(input().strip())
a = list(map(int, input().strip().split()[1:]))
b = list(map(int, input().strip().split()[1:]))
steps = 0
while len(a) and len(b):
	x = a.pop(0)
	y = b.pop(0)
	if x > y:
		a += [y, x]
	else:
		b += [x, y]
	steps += 1
	if steps > 110:
		print(-1)
		quit()
if a == []:
	print(steps, 2)
else:
	print(steps, 1)


n = int(input())
a = [int(i) for i in input().split()]
a.remove(a[0])
b = [int(i) for i in input().split()]
b.remove(b[0])
k = 0
while len(a) > 0 and len(b) > 0:
	if a[0] > b[0]:
		a.append(b[0])
		a.append(a[0])
		a.remove(a[0])
		b.remove(b[0])
	else:
		b.append(a[0])
		b.append(b[0])
		b.remove(b[0])
		a.remove(a[0])
	k += 1
	if k > 700000:
		print(-1)
		exit(0)
if len(a) > 0:
	print(k, 1)
else:
	print(k, 2)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
import sys
input = sys.stdin.readline
scanner = lambda : int(input())
string = lambda : input().rstrip()
get_list = lambda : list(read())
read = lambda : map(int, input().split())
get_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def is_integer(n):
	return math.ceil(n) == math.floor(n)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(beauty, s, n, count):
	pass
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
alphs = 'abcdefghijklmnopqrstuvwxyz'
from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect

def solve():
	n = scanner()
	(l, *a) = get_list()
	(r, *b) = get_list()
	a = collect.deque(a)
	b = collect.deque(b)
	s = 0
	while a and b:
		s += 1
		if s > 1000:
			print(-1)
			return
		(x, y) = (a.popleft(), b.popleft())
		if x > y:
			a.append(y)
			a.append(x)
		else:
			b.append(x)
			b.append(y)
	if a:
		print(s, 1)
	else:
		print(s, 2)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i in range(1):
	solve()


n = int(input())
a1 = list(map(int, input().split()))[1:]
a2 = list(map(int, input().split()))[1:]
cnt = 0
while a1 != [] and a2 != []:
	cnt += 1
	if cnt > 1000000:
		print(-1)
		exit(0)
	(t1, t2) = (a1.pop(0), a2.pop(0))
	if t1 > t2:
		a1 += [t2, t1]
	else:
		a2 += [t1, t2]
print(cnt, 1 if a1 != [] else 2)


from typing import List, Union

def solve(n: int, k1: List[int], k2: List[int]) -> Union[int, str]:
	visited = set()
	pos = (k1[1:], k2[1:])
	fights = 0
	while True:
		if str(pos) in visited:
			return -1
		if len(pos[0]) == 0 or len(pos[1]) == 0:
			return '{0} {1}'.format(fights, [1, 2][len(pos[0]) == 0])
		visited.add(str(pos))
		fights += 1
		if pos[0][0] > pos[1][0]:
			pos = (pos[0][1:] + [pos[1][0], pos[0][0]], pos[1][1:])
		else:
			pos = (pos[0][1:], pos[1][1:] + [pos[0][0], pos[1][0]])
n = input()
k1 = list(map(int, input().split()))
k2 = list(map(int, input().split()))
print(solve(n, k1, k2))


n = int(input())
xs1 = [int(x) for x in input().split()][1:]
xs2 = [int(x) for x in input().split()][1:]
xs1.reverse()
xs2.reverse()
states = {}

def hashe(xs):
	s = ''
	for x in xs:
		s += str(x)
	return s
games = 0
while True:
	state = hashe(xs1) + hashe(xs2)
	if state in states:
		print(-1)
		break
	states[state] = True
	x1 = xs1.pop()
	x2 = xs2.pop()
	if x1 > x2:
		xs1.insert(0, x2)
		xs1.insert(0, x1)
	else:
		xs2.insert(0, x1)
		xs2.insert(0, x2)
	games += 1
	if len(xs1) is 0:
		print(games, 2)
		break
	elif len(xs2) is 0:
		print(games, 1)
		break


n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
m1 = l1[1:]
m2 = l2[1:]
(c, c1, f) = (0, 0, 0)
while len(m1) != 0 and len(m2) != 0:
	if m1[0] < m2[0]:
		c = m1.pop(0)
		m2.append(c)
		c = m2.pop(0)
		m2.append(c)
	else:
		c = m2.pop(0)
		m1.append(c)
		c = m1.pop(0)
		m1.append(c)
	c1 += 1
	if c1 > n * n * n or (m1 == l1[1:] and m2 == l2[1:]):
		f = 1
		break
if f == 1:
	print(-1)
elif len(m1) == 0:
	print(c1, 2)
else:
	print(c1, 1)


from collections import deque
n = int(input())
q1 = deque(list(map(int, input().split()))[1:])
q2 = deque(list(map(int, input().split()))[1:])
ans = 0
visited = {}
(s1, s2) = ('', '')
for i in q1:
	s1 = s1 + str(i)
for i in q2:
	s2 = s2 + str(i)
s = frozenset([s1, s2])
visited[s] = visited.get(s, 0) + 1
while len(q1) and len(q2):
	x = q1.popleft()
	y = q2.popleft()
	if x > y:
		q1.append(y)
		q1.append(x)
	else:
		q2.append(x)
		q2.append(y)
	(s1, s2) = ('', '')
	for i in q1:
		s1 = s1 + str(i)
	for i in q2:
		s2 = s2 + str(i)
	s = frozenset([s1, s2])
	visited[s] = visited.get(s, 0) + 1
	if visited[s] == 1:
		ans = ans + 1
	else:
		ans = -1
		break
if ans == -1:
	print(ans)
else:
	if len(q1) > len(q2):
		l = 1
	else:
		l = 2
	print(ans, l)


def maker(a, b):
	(m, n) = ('', '')
	for i in a:
		m = m + str(i)
	for i in b:
		n = n + str(i)
	return (m, n)
n = int(input())
a = list(map(int, input().split()))
a.pop(0)
b = list(map(int, input().split()))
b.pop(0)
c = set()
c.add(maker(a, b))
f = True
fights = 0
while 1:
	fights += 1
	(x, y) = (a.pop(0), b.pop(0))
	if x < y:
		b.append(x)
		b.append(y)
	else:
		a.append(y)
		a.append(x)
	u = maker(a, b)
	if len(a) == 0 or len(b) == 0:
		print(fights, end=' ')
		if len(a) != 0:
			print('1')
		else:
			print('2')
		break
	elif u in c:
		print('-1')
		break
	else:
		c.add(u)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
del a[0]
del b[0]
c = 0
while True:
	if a[0] > b[0]:
		a.append(b[0])
		a.append(a[0])
		del a[0]
		del b[0]
	else:
		b.append(a[0])
		b.append(b[0])
		del a[0]
		del b[0]
	c = c + 1
	if a == []:
		print(c)
		print('2')
		break
	elif b == []:
		print(c)
		print('1')
		break
	elif c > min(2 ** n, 150):
		print('-1')
		break


n = int(input())
l = list(map(int, input().split()))
m = list(map(int, input().split()))
c = 0
l = l[1:]
m = m[1:]
(q1, q2) = ([], [])
q1.extend(l)
q2.extend(m)
while len(l) > 0 and len(m) > 0:
	(a, b) = (l.pop(0), m.pop(0))
	if a > b:
		l.append(b)
		l.append(a)
	else:
		m.append(a)
		m.append(b)
	c += 1
	if c > 500:
		c = -1
		break
if c == -1:
	print(-1)
else:
	x = 2
	if len(l) > 0:
		x = 1
	print(c, x)


N = input()
s1 = input().split(' ')[1:]
s2 = input().split(' ')[1:]
s1 = tuple(map(int, s1))
s2 = tuple(map(int, s2))
visited = set()
count = 0
while len(s1) > 0 and len(s2) > 0:
	count += 1
	if (s1, s2) in visited:
		break
	else:
		visited.add((s1, s2))
	if s1[0] < s2[0]:
		s2 = s2[1:] + (s1[0], s2[0])
		s1 = s1[1:]
	else:
		s1 = s1[1:] + (s2[0], s1[0])
		s2 = s2[1:]
if len(s1) == 0:
	print(str(count) + ' 2')
elif len(s2) == 0:
	print(str(count) + ' 1')
else:
	print(-1)


import os
import sys
from io import BytesIO, IOBase
import math
from itertools import permutations
from decimal import Decimal, getcontext
getcontext().prec = 25
MOD = pow(10, 9) + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = int(input())
l1 = list(map(int, input().split(' ')))
l2 = list(map(int, input().split(' ')))
a = l1[0]
l1.pop(0)
b = l2[0]
l2.pop(0)
x = [0] * 10000
y = [0] * 10000
for i in range(a):
	x[i] = l1[i]
for i in range(b):
	y[i] = l2[i]
ans = -1
ans2 = 0
for i in range(997):
	if not x[i] or not y[i]:
		if x[i]:
			ans = 1
		else:
			ans = 2
		break
	elif x[i] > y[i]:
		x[a] = y[i]
		x[a + 1] = x[i]
		a += 2
	else:
		y[b] = x[i]
		y[b + 1] = y[i]
		b += 2
	ans2 += 1
if ans != -1:
	print(ans2, ans)
else:
	print(-1)


n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
l1.pop(0)
l2.pop(0)
count = 0
while l1 and l2:
	if count >= 100000:
		print('-1')
		exit()
	count += 1
	t1 = l1.pop(0)
	t2 = l2.pop(0)
	if t1 > t2:
		l1 += [t2, t1]
	else:
		l2 += [t1, t2]
if l1:
	print(count, 1)
else:
	print(count, 2)


from math import factorial
from sys import stdin
input = stdin.readline
input()
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
s = set()
e = False
cnt = 0
while len(a) * len(b):
	(c, d) = (a.pop(0), b.pop(0))
	if c > d:
		a += [d, c]
	else:
		b += [c, d]
	cnt += 1
	t = (tuple(a), tuple(b))
	if t in s:
		e = True
		break
	s.add(t)
if e:
	print(-1)
else:
	print(cnt, [1, 2][len(a) == 0])


max_count = 1000
input()
a = list(map(int, input().split()[1:]))
b = list(map(int, input().split()[1:]))
i = 0
while len(a) - i > 0 and len(b) - i > 0 and (i < max_count):
	if a[i] > b[i]:
		a.extend([b[i], a[i]])
	else:
		b.extend([a[i], b[i]])
	i += 1
print(-1 if i == max_count else ' '.join(map(str, (i, 1))) if len(b) - i == 0 else ' '.join(map(str, (i, 2))))


n = int(input())
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))
s1 = s1[1:]
s2 = s2[1:]
count = 0
while len(s1) != 0 and len(s2) != 0:
	if s1[0] > s2[0]:
		s1.append(s2[0])
		s1.append(s1[0])
		s1 = s1[1:]
		s2 = s2[1:]
	elif count > 500:
		break
	else:
		s2.append(s1[0])
		s2.append(s2[0])
		s2 = s2[1:]
		s1 = s1[1:]
	count = count + 1
if len(s1) == 0:
	print(count, end=' ')
	print('2')
elif len(s2) == 0:
	print(count, end=' ')
	print('1')
elif count > 500:
	print('-1')


I = lambda : list(map(int, input().split()))[1:]
I()
a = I()
b = I()
t = 0
while t < 10 ** 5 and a and b:
	t += 1
	if a[0] > b[0]:
		a += [b[0], a[0]]
	else:
		b += [a[0], b[0]]
	a = a[1:]
	b = b[1:]
print([str(t) + ' ' + str(1 + bool(b)), -1][t == 10 ** 5])


import sys
n = int(input())
(a, b) = (list(map(int, input().split())), list(map(int, input().split())))
step = 0
i = 0
a.pop(i)
b.pop(i)
hist = list()
while a != [] and b != []:
	if [a, b] in hist:
		print(-1)
		sys.exit(0)
	hist.append([[x for x in a], [x for x in b]])
	if a[i] > b[i]:
		a.append(b[i])
		a.append(a[i])
	else:
		b.append(a[i])
		b.append(b[i])
	a.pop(i)
	b.pop(i)
	step += 1
print(step, 2 if a == [] else 1)


z = lambda : list(map(int, input().split()))
n = int(input())
k1 = z()[1:]
k2 = z()[1:]
c = 0
while k1 and k2:
	(x, y) = (k1.pop(0), k2.pop(0))
	if x > y:
		k1 += [y, x]
	else:
		k2 += [x, y]
	if c > 1000:
		print(-1)
		break
	c += 1
else:
	print(c, 1 if k1 else 2)


n = int(input())
k1 = list(map(int, input().split()))
k1.pop(0)
k2 = list(map(int, input().split()))
k2.pop(0)
trick = 0
while k1 and k2:
	trick += 1
	if trick > 110:
		print(-1)
		exit()
	a = k1.pop(0)
	b = k2.pop(0)
	if a > b:
		k1.append(b)
		k1.append(a)
	else:
		k2.append(a)
		k2.append(b)
print(str(trick) + ' ' + str(1 if k1 else 2))


import os
import sys
from io import BytesIO, IOBase

def main():
	n = input()
	a = list(map(int, input().split(' ')))[1:]
	b = list(map(int, input().split(' ')))[1:]
	temp = max(a + b)
	if a.count(temp) > 0 and b.count(temp) > 0:
		print(-1)
	else:
		chk = 0
		cnt = 0
		while len(a) > 0 and len(b) > 0:
			if a[0] > b[0]:
				a = a[1:] + b[0:1] + a[0:1]
				b = b[1:]
			elif b[0] > a[0]:
				b = b[1:] + a[0:1] + b[0:1]
				a = a[1:]
			else:
				a = a[1:] + a[0:1]
				b = b[1:] + b[0:1]
			cnt += 1
			if cnt > 1000:
				chk = 1
				break
		if chk == 1:
			print(-1)
		elif len(b) == 0:
			print(cnt, 1)
		else:
			print(cnt, 2)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def main():
	n = int(input())
	temp = input().split()
	p1n = int(temp[0])
	p1cards = [int(i) for i in temp[1:]]
	temp = input().split()
	p2n = int(temp[0])
	p2cards = [int(i) for i in temp[1:]]
	stale = False
	history1 = []
	history2 = []
	counter = 0
	while len(p1cards) != 0 and len(p2cards) != 0 and (stale == False):
		counter += 1
		history1.append(p1cards)
		history2.append(p2cards)
		if p1cards[0] > p2cards[0]:
			(p1cards, p2cards) = switchero(p1cards, p2cards)
		elif p2cards[0] > p1cards[0]:
			(p2cards, p1cards) = switchero(p2cards, p1cards)
		for cards1 in history1:
			if p1cards == cards1:
				for cards2 in history2:
					if p2cards == cards2:
						stale = True
					continue
	if stale == True:
		counter = -1
	if len(p1cards) == 0:
		winner = 2
		print(counter, winner)
	elif len(p2cards) == 0:
		winner = 1
		print(counter, winner)
	else:
		print(counter)

def switchero(winner, loser):
	if len(loser) == 1:
		losernew = []
	else:
		losernew = loser[1:]
	winnernew = winner[1:]
	winnernew.append(loser[0])
	winnernew.append(winner[0])
	return (winnernew, losernew)
main()


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 0
(a.pop(0), b.pop(0))
while a and b:
	if ans > 110:
		print(-1)
		exit(0)
	ans += 1
	x = a.pop(0)
	y = b.pop(0)
	if x > y:
		a.append(y)
		a.append(x)
	else:
		b.append(x)
		b.append(y)
if a:
	print(ans, 1)
else:
	print(ans, 2)


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

def in_int():
	return int(input())

def in_list():
	return list(map(int, input().split()))

def in_str():
	s = input()
	return list(s[:len(s) - 1])

def in_ints():
	return map(int, input().split())
n = in_int()
a = in_list()
b = in_list()
xx = a.pop(0)
xx = b.pop(0)
ss = set()
count = 0
while str(a) + str(b) not in ss and len(a) > 0 and (len(b) > 0):
	ss.add(str(a) + str(b))
	aa = a.pop(0)
	bb = b.pop(0)
	if aa > bb:
		a = a + [bb, aa]
	else:
		b = b + [aa, bb]
	count += 1
if len(a) == 0:
	print(count, 2)
elif len(b) == 0:
	print(count, 1)
else:
	print(-1)


from sys import stdout
from sys import stdin

def get():
	return stdin.readline().strip()

def getf(sp=' '):
	return [int(i) for i in get().split(sp)]

def put(a, end='\n'):
	stdout.write(str(a) + end)

def putf(a, sep=' ', end='\n'):
	stdout.write(sep.join([str(i) for i in a]) + end)
from collections import deque

def main():
	n = int(get())
	(k1, *a) = getf()
	(k2, *b) = getf()
	a = deque(a[::-1])
	b = deque(b[::-1])
	st = set()
	st.add((tuple(a), tuple(b)))
	f = -1
	res = 0
	while True:
		x = a.pop()
		y = b.pop()
		res += 1
		if x > y:
			a.appendleft(y)
			a.appendleft(x)
			k1 += 1
			k2 -= 1
		else:
			b.appendleft(x)
			b.appendleft(y)
			k1 -= 1
			k2 += 1
		if k1 == 0:
			f = 1
			break
		if k2 == 0:
			f = 0
			break
		i = (tuple(a), tuple(b))
		if i in st:
			break
		st.add(i)
	if f == -1:
		put('-1')
	else:
		put('%d %d' % (res, f + 1))
main()


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
from heapq import *
from math import gcd, factorial, floor, ceil
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 10 ** 9 + 7

def solve(case):
	n = int(inp())
	a = deque(lis())
	b = deque(lis())
	a.popleft()
	b.popleft()
	cnt = 0
	while len(a) != 0 and len(b) != 0:
		x = a.popleft()
		y = b.popleft()
		if x < y:
			b.append(x)
			b.append(y)
		else:
			a.append(y)
			a.append(x)
		cnt += 1
		if cnt > 200:
			print(-1)
			return
	if len(a) == 0:
		print(cnt, 2)
	else:
		print(cnt, 1)
testcase(1)


from collections import deque

def wars():
	n = int(input())
	cards = input().split()
	tot = int(cards[0])
	queue1 = deque((int(i) for i in cards[1:]))
	test = queue1
	queue2 = deque((int(i) for i in input().split()[1:]))
	c = 0
	while queue1 and queue2:
		if c > 5000:
			return -1
		c1 = queue1.popleft()
		c2 = queue2.popleft()
		c += 1
		if c1 > c2:
			queue1.append(c2)
			queue1.append(c1)
		else:
			queue2.append(c1)
			queue2.append(c2)
	w = '1' if queue1 else '2'
	return str(c) + ' ' + w
print(wars())


def lista_string_int(l):
	for i in range(len(l)):
		l[i] = int(l[i])
n = int(input())
l1 = list(input().split(' '))
l2 = list(input().split(' '))
n1 = l1.pop(0)
n2 = l2.pop(0)
lista_string_int(l1)
lista_string_int(l2)
ganador = False
for i in range(5000):
	if len(l1) == 0:
		ganador = True
		print(i, 2)
		break
	elif len(l2) == 0:
		ganador = True
		print(i, 1)
		break
	if l1[0] > l2[0]:
		l1.append(l2.pop(0))
		l1.append(l1.pop(0))
	elif l2[0] > l1[0]:
		l2.append(l1.pop(0))
		l2.append(l2.pop(0))
if ganador == False:
	print(-1)


n = int(input())
list1 = list(map(int, input().split()))
list2 = list(map(int, input().split()))
k1 = list1[0]
del list1[0]
k2 = list2[0]
del list2[0]
i = 0
count = 0
while len(list1) != 0 and len(list2) != 0:
	if list1[i] < list2[i]:
		list2.append(list1[i])
		list2.append(list2[i])
		del list1[i]
		del list2[i]
		count += 1
	elif list2[i] < list1[i]:
		list1.append(list2[i])
		list1.append(list1[i])
		del list1[i]
		del list2[i]
		count += 1
	else:
		del list1[i]
		del list2[i]
	if count == n ** 2 + 10:
		print('-1')
		break
if len(list1) == 0:
	print('{} 2'.format(count))
if len(list2) == 0:
	print('{} 1'.format(count))


n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
res = 0
l1 = l1[1:]
l2 = l2[1:]
while len(l1) > 0 and len(l2) > 0:
	res += 1
	if res > 1000:
		break
	x = l1.pop(0)
	y = l2.pop(0)
	if x > y:
		l1.append(y)
		l1.append(x)
	else:
		l2.append(x)
		l2.append(y)
if len(l2) == 0:
	print(res, end=' ')
	print(1)
elif len(l1) == 0:
	print(res, end=' ')
	print(2)
else:
	print(-1)


n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
k1 = a.pop(0)
k2 = b.pop(0)
flag = False
cnt = 0
n = 106
while k1 != 0 and k2 != 0 and (n > 0):
	n -= 1
	cnt += 1
	x = a.pop(0)
	y = b.pop(0)
	if x > y:
		a.append(y)
		a.append(x)
		k1 += 1
		k2 -= 1
	else:
		b.append(x)
		b.append(y)
		k2 += 1
		k1 -= 1
if k1 != 0 and k2 != 0:
	print('-1')
else:
	print(cnt, '1' if k1 != 0 else '2')


import sys

def solve(n, f, s):
	moves = 0
	max_till = 200
	while f and s:
		if f[0] > s[0]:
			f.append(s[0])
			f.append(f[0])
			s.pop(0)
			f.pop(0)
			moves += 1
		else:
			s.append(f[0])
			s.append(s[0])
			s.pop(0)
			f.pop(0)
			moves += 1
		if moves > max_till:
			return -1
	if not f:
		return (moves, 2)
	else:
		return (moves, 1)
take = sys.stdin.readline
n = int(take())
f = list(map(int, take().split()))[1:]
s = list(map(int, take().split()))[1:]
result = solve(n, f, s)
if result == -1:
	print(-1)
	exit(0)
print(*result)


def is_loop(l1, l2, cards_sets=[]):
	card_set = set([tuple(l1), tuple(l2)])
	if card_set in cards_sets:
		return True
	else:
		cards_sets.append(card_set)
		return False
cards_amount = int(input())
first_player = input().split()[1:]
first_player = [int(i) for i in first_player]
second_player = input().split()[1:]
second_player = [int(i) for i in second_player]
result = 0
while True:
	if is_loop(first_player, second_player):
		print(-1)
		break
	result += 1
	fp_card = first_player.pop(0)
	sp_card = second_player.pop(0)
	if fp_card > sp_card:
		first_player.extend([sp_card, fp_card])
	else:
		second_player.extend([fp_card, sp_card])
	if not second_player:
		print(result, 1)
		break
	if not first_player:
		print(result, 2)
		break


n = int(input())
ls1 = list(map(int, input().split()))
ls2 = list(map(int, input().split()))
del ls1[0]
del ls2[0]
cp1 = []
cp2 = []
for i in ls1:
	cp1.append(i)
for i in ls2:
	cp2.append(i)
fights = 0
flag = 0
while len(ls1) != 0 and len(ls2) != 0:
	if fights > 1000:
		flag += 1
		break
	if ls1[0] > ls2[0]:
		ls1.append(ls2[0])
		ls1.append(ls1[0])
		del ls1[0]
		del ls2[0]
	else:
		ls2.append(ls1[0])
		ls2.append(ls2[0])
		del ls1[0]
		del ls2[0]
	if ls1 == cp1 and ls2 == cp2:
		flag += 1
		break
	fights += 1
if flag != 0:
	print(-1)
elif len(ls1) != 0:
	print(fights, 1)
else:
	print(fights, 2)


def fight(k1, k2):
	l = k1.pop(0)
	r = k2.pop(0)
	if l < r:
		k2.extend([l, r])
	else:
		k1.extend([r, l])
n = int(input())
k1 = list(map(int, input().split()))
k1.pop(0)
k2 = list(map(int, input().split()))
k2.pop(0)
combs = set()
fights = 0
while k1 and k2:
	topcomb = (''.join(map(str, k1)), ''.join(map(str, k2)))
	if topcomb in combs:
		fights = -1
		break
	combs.add(topcomb)
	fight(k1, k2)
	fights += 1
print(fights, end=' ')
if fights > -1:
	print(1 if k1 else 2)


import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
k1 = list(map(int, input().split()))
k2 = list(map(int, input().split()))
e1 = deque(k1)
e2 = deque(k2)
e1.popleft()
e2.popleft()
ans = 0
while len(e1) > 0 and len(e2) > 0 and (ans < 10 ** 7):
	x1 = e1.popleft()
	x2 = e2.popleft()
	if x1 > x2:
		e1.append(x2)
		e1.append(x1)
	else:
		e2.append(x1)
		e2.append(x2)
	ans += 1
if ans == 10 ** 7:
	print(-1)
	exit()
if len(e2) == 0:
	print(ans, 1)
else:
	print(ans, 2)


n = int(input())
q1 = list(map(int, input().split()))[1:]
q2 = list(map(int, input().split()))[1:]
s = set()
c = 0
while q1 and q2:
	c += 1
	a = q1.pop(0)
	b = q2.pop(0)
	if a < b:
		q2.append(a)
		q2.append(b)
	else:
		q1.append(b)
		q1.append(a)
	t = (tuple(q1), tuple(q2))
	if t in s:
		break
	s.add(t)
if q1 and q2:
	print(-1)
else:
	print(c, 1 if q1 else 2)


n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
for ans in range(1, 100000):
	if a[0] < b[0]:
		b.append(a.pop(0))
		b.append(b.pop(0))
	else:
		a.append(b.pop(0))
		a.append(a.pop(0))
	if not a or not b:
		print(ans, 1 if a else 2)
		break
else:
	print(-1)


from collections import deque
n = int(input())
p1 = deque(map(int, input().split()))
p2 = deque(map(int, input().split()))
k1 = p1.popleft()
k2 = p2.popleft()
for i in range(int(40000000.0)):
	a = p1.popleft()
	b = p2.popleft()
	if a > b:
		p1.append(b)
		p1.append(a)
	else:
		p2.append(a)
		p2.append(b)
	if not p1 or not p2:
		print(i + 1, end=' ')
		if n in p1:
			print(1)
		else:
			print(2)
		exit(0)
print(-1)


n = int(input())
p1 = list(map(int, input().split()))
p2 = list(map(int, input().split()))
p1_score = 0
p2_score = 0
p1.pop(0)
p2.pop(0)
prev_stacks = []
found = False
while p1 and p2:
	prev_stacks.append(str(p1) + '/' + str(p2))
	x = p1.pop(0)
	y = p2.pop(0)
	if x > y:
		p1_score += 1
		p1.append(y)
		p1.append(x)
	else:
		p2_score += 1
		p2.append(x)
		p2.append(y)
	if str(p1) + '/' + str(p2) in prev_stacks:
		found = True
		break
if found or p1_score == p2_score:
	print(-1)
else:
	winner = 0
	if p1_score > p2_score:
		winner = 1
	else:
		winner = 2
	print(p1_score + p2_score, winner)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nlargest, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
n = int(data())
(s1, s2) = (deque(l()[1:]), deque(l()[1:]))
state = set()
state.add((tuple(s1), tuple(s2)))
cnt = 0
while True:
	(t1, t2) = (s1.popleft(), s2.popleft())
	if t1 > t2:
		s1.append(t2)
		s1.append(t1)
	else:
		s2.append(t1)
		s2.append(t2)
	if not s1:
		out(cnt + 1, 2)
		exit()
	if not s2:
		out(cnt + 1, 1)
		exit()
	cnt += 1
	if (tuple(s1), tuple(s2)) in state or (tuple(s2), tuple(s1)) in state:
		out(-1)
		exit()
	state.add((tuple(s1), tuple(s2)))


from collections import deque

def main():
	n = int(input())
	a = deque([int(c) for c in input().split()][::-1])
	b = deque([int(c) for c in input().split()][::-1])
	a.pop()
	b.pop()
	conf = set()
	i = 1
	while True:
		cur = (tuple(a), tuple(b))
		if cur in conf:
			print(-1)
			return
		else:
			conf.add(cur)
		(x, y) = (a.pop(), b.pop())
		if x > y:
			a.appendleft(y)
			a.appendleft(x)
		else:
			b.appendleft(x)
			b.appendleft(y)
		if not a:
			print(i, 2)
			return
		if not b:
			print(i, 1)
			return
		i += 1
main()


from collections import defaultdict as dd, deque as dq
from math import factorial
p = int(input())
(a1, *a) = list(map(int, input().split()))
(b1, *b) = list(map(int, input().split()))
t = factorial(11)
m = dq(a)
n = dq(b)
d = {}
fights = 0
while m and n:
	if fights > t:
		fights = -1
		break
	k = m.popleft()
	l = n.popleft()
	if k > l:
		m.append(l)
		m.append(k)
	else:
		n.append(k)
		n.append(l)
	fights += 1
if fights == -1:
	print(fights)
elif list(m) == []:
	print(fights, 2)
else:
	print(fights, 1)


n = int(input())
l1 = [int(i) for i in input().split()]
k1 = l1.pop(0)
l1.reverse()
l2 = [int(i) for i in input().split()]
k2 = l2.pop(0)
l2.reverse()
i = 0
dup = set()
while len(l1) > 0 and len(l2) > 0:
	c = tuple(l1 + [0.5] + l2)
	if c in dup:
		break
	dup.add(c)
	a = l1.pop()
	b = l2.pop()
	if a > b:
		l1.insert(0, b)
		l1.insert(0, a)
	else:
		l2.insert(0, a)
		l2.insert(0, b)
	i += 1
if len(l1) == 0:
	print(i, 2)
elif len(l2) == 0:
	print(i, 1)
else:
	print(-1)


from copy import deepcopy
n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
data = []
count = 0
while a and b:
	if (a, b) in data:
		print(-1)
		break
	data.append((deepcopy(a), deepcopy(b)))
	if a > b:
		a += [b.pop(0), a.pop(0)]
	elif a < b:
		b += [a.pop(0), b.pop(0)]
	count += 1
if not a or not b:
	print(count, 1 if a else 2)


n = int(input())
c_1 = [int(x) for x in input().split()]
c_1.pop(0)
c_2 = [int(x) for x in input().split()]
c_2.pop(0)
reached_before = dict()
reached_before[str(c_1) + ' ' + str(c_2)] = True
cntr = 0
over = False
while not over:
	card_1 = c_1.pop(0)
	card_2 = c_2.pop(0)
	if card_1 > card_2:
		c_1.append(card_2)
		c_1.append(card_1)
	else:
		c_2.append(card_1)
		c_2.append(card_2)
	cntr += 1
	if not c_1:
		over = True
		print(cntr, 2)
	elif not c_2:
		over = True
		print(cntr, 1)
	elif reached_before.get(str(c_1) + ' ' + str(c_2)):
		over = True
		print(-1)
	else:
		reached_before[str(c_1) + ' ' + str(c_2)] = True


def main():
	n = int(input())
	a = list(map(int, input().split()))[1:]
	b = list(map(int, input().split()))[1:]
	st = set()
	st.add((tuple(a), tuple(b)))
	t = 0
	while len(a) and len(b):
		t += 1
		if a[0] > b[0]:
			a.extend([b[0], a[0]])
		else:
			b.extend([a[0], b[0]])
		a.pop(0)
		b.pop(0)
		if (tuple(a), tuple(b)) in st:
			print(-1)
			return 0
		st.add((tuple(a), tuple(b)))
	print(t, 1 + (len(a) == 0))
main()


def winner(a: list, b: list) -> int:
	if a == []:
		return 2
	elif b == []:
		return 1
	else:
		return -1

def _compare(_f_list: list, _s_list: list, f: int, s: int) -> None:
	if max(f, s) == f:
		_f_list.append(min(f, s))
		_f_list.append(max(f, s))
	else:
		_s_list.append(min(f, s))
		_s_list.append(max(f, s))

def swap(_F_list: list, _S_list: list) -> None:
	(F_out, S_out) = (_F_list[0], _S_list[0])
	del _F_list[0]
	del _S_list[0]
	_compare(_F_list, _S_list, F_out, S_out)
number = int(input())
(F, S) = ([], [])
temp_list = []
F = list(map(int, input().split()))
S = list(map(int, input().split()))
del F[0]
del S[0]
(dup_F, dup_S) = ([], [])
for i in range(len(F)):
	dup_F.append(F[i])
for i in range(len(S)):
	dup_S.append(S[i])
current_situ = []
current_situ.append(dup_F)
current_situ.append(dup_S)
temp_list.append(current_situ)
time = 0
OMG = False
while winner(F, S) == -1:
	if time >= 1:
		(dup_F, dup_S) = ([], [])
		for i in range(len(F)):
			dup_F.append(F[i])
		for i in range(len(S)):
			dup_S.append(S[i])
		current_situ = []
		current_situ.append(dup_F)
		current_situ.append(dup_S)
		temp_list.append(current_situ)
		for i in temp_list[:-1]:
			if current_situ == i:
				OMG = True
	if OMG:
		break
	swap(F, S)
	time += 1
if winner(F, S) != -1:
	print(time, end=' ')
	print(winner(F, S))
else:
	print(winner(F, S))


from sys import stdin, stdout
n = int(stdin.readline())
array1 = list(map(int, stdin.readline().split()))[1:]
array2 = list(map(int, stdin.readline().split()))[1:]
i = 0
while array1 and array2 and (i < 1000):
	if array1[0] > array2[0]:
		array1.append(array2[0])
		array1.append(array1[0])
		i += 1
	else:
		array2.append(array1[0])
		array2.append(array2[0])
		i += 1
	array1.pop(0)
	array2.pop(0)
if len(array1) == 0:
	stdout.write(str(i) + ' ' + '2' + '\n')
elif len(array2) == 0:
	stdout.write(str(i) + ' ' + '1' + '\n')
else:
	stdout.write('-1' + '\n')


from collections import deque
n = int(input())
a = deque([int(i) for i in input().split()[1:]])
b = deque([int(i) for i in input().split()[1:]])
mark = set()
ans = 0
while a and b:
	if str(a) + ' ' + str(b) in mark:
		print(-1)
		exit()
	mark.add(str(a) + ' ' + str(b))
	ans += 1
	aa = a.popleft()
	bb = b.popleft()
	if aa > bb:
		a.append(bb)
		a.append(aa)
	else:
		b.append(aa)
		b.append(bb)
if a:
	print(ans, 1)
else:
	print(ans, 2)


n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
c = 0
s = set()
s.add(tuple(a) + tuple('#') + tuple(b))
flag = 1
while a and b and flag:
	c1 = a[0]
	c2 = b[0]
	a = a[1:]
	b = b[1:]
	if c1 < c2:
		b += [c1] + [c2]
	else:
		a += [c2] + [c1]
	k = tuple(a) + tuple('#') + tuple(b)
	if k in s:
		print(-1)
		flag = 0
	else:
		s.add(k)
	c += 1
if flag:
	if a:
		print(c, 1)
	else:
		print(c, 2)


import os, io
import sys

def binomial_coefficient(n, k):
	if 0 <= k <= n:
		ntok = 1
		ktok = 1
		for t in range(1, min(k, n - k) + 1):
			ntok *= n
			ktok *= t
			n -= 1
		return ntok // ktok
	else:
		return 0

def getState(d1, d2):
	return ''.join(d1) + '-' + ''.join(d2)
n = int(sys.stdin.readline().strip())
d1 = sys.stdin.readline().strip().split(' ')[1:]
d2 = sys.stdin.readline().strip().split(' ')[1:]
states = set([getState(d1, d2)])
possible = True
cnt = 0
while len(d1) and len(d2):
	c1 = d1.pop(0)
	c2 = d2.pop(0)
	if int(c1) > int(c2):
		d1.append(c2)
		d1.append(c1)
	else:
		d2.append(c1)
		d2.append(c2)
	state = getState(d1, d2)
	cnt += 1
	if state in states:
		print(-1)
		possible = False
		break
	states.add(state)
if possible:
	print(cnt, end=' ')
	if len(d1):
		print('1')
	else:
		print('2')


class Soldado:

	def __init__(self, cartas, numero):
		cartas = cartas[1:]
		self.mano = cartas.split()
		self.nombre = numero

	def perder(self):
		if len(self.mano) > 0:
			self.mano.remove(self.mano[0])

	def ganar(self, otro_soldado):
		self.mano.append(otro_soldado.mano[0])
		self.mano.append(self.mano[0])
		self.mano.remove(self.mano[0])

	def __gt__(self, otro_soldado):
		return int(self.mano[0]) > int(otro_soldado.mano[0])

	def __lt__(self, otro_soldado):
		return int(self.mano[0]) < int(otro_soldado.mano[0])

	def __eq__(self, otro_soldado):
		return len(self.mano) == len(otro_soldado.mano)

	def __str__(self):
		print(self.nombre)
mazo = int(input())
cartas1 = input()
cartas2 = input()
soldado1 = Soldado(cartas1, 1)
soldado2 = Soldado(cartas2, 2)
juego = True
t = 0
while juego == True:
	if soldado1 > soldado2:
		soldado1.ganar(soldado2)
		soldado2.perder()
		t += 1
	elif soldado1 < soldado2:
		soldado2.ganar(soldado1)
		soldado1.perder()
		t += 1
	if t > 500:
		print('-1')
		juego = False
	elif len(soldado1.mano) == 0:
		juego = False
		print(str(t) + ' ' + '2')
	elif len(soldado2.mano) == 0:
		juego = False
		print(str(t) + ' ' + '1')


n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
used = set()
cnt = 0
while len(a) != 0 and len(b) != 0:
	if (tuple(a), tuple(b)) not in used:
		used.add((tuple(a), tuple(b)))
	else:
		print(-1)
		return
	(x, y) = (a.pop(0), b.pop(0))
	if x > y:
		a.append(y)
		a.append(x)
	else:
		b.append(x)
		b.append(y)
	cnt += 1
print(cnt, '1' if len(b) == 0 else '2')


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = a[1:]
x = a
b = b[1:]
y = b
f = -1
cnt = 0
while cnt < 500:
	k1 = a.pop(0)
	k2 = b.pop(0)
	if k1 > k2:
		a.append(k2)
		a.append(k1)
	else:
		b.append(k1)
		b.append(k2)
	cnt += 1
	if len(a) == 0:
		f = 2
		break
	if len(b) == 0:
		f = 1
		break
if cnt == 500 or f == -1:
	print(-1)
else:
	print(cnt, f)


import time
start_time = time.time()
n = int(input())
fir = list(map(int, input().split()))
sec = list(map(int, input().split()))
fir.pop(0)
sec.pop(0)
fight_cnt = 0
impossible = False
while fir and sec:
	fir_card = fir.pop(0)
	sec_card = sec.pop(0)
	if fir_card > sec_card:
		fir.append(sec_card)
		fir.append(fir_card)
	else:
		sec.append(fir_card)
		sec.append(sec_card)
	fight_cnt += 1
	if time.time() - start_time > 1.9:
		impossible = True
		break
if impossible:
	print(-1)
else:
	print(fight_cnt, 1 if fir else 2)


n = int(input())
l1 = list(map(int, input().split()))
k1 = l1[0]
del l1[0]
l2 = list(map(int, input().split()))
k2 = l2[0]
del l2[0]
org_state1 = l1[:]
org_state2 = l2[:]
occured_states = [[org_state1, org_state2]]
count = 0
while l1 != [] and l2 != []:
	c1 = l1.pop(0)
	c2 = l2.pop(0)
	if c1 > c2:
		l1.append(c2)
		l1.append(c1)
	else:
		l2.append(c1)
		l2.append(c2)
	if [l1, l2] not in occured_states:
		occured_states.append([l1[:], l2[:]])
		count += 1
	else:
		print(-1)
		break
if l1 == []:
	print(count, 2)
elif l2 == []:
	print(count, 1)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
(k, l) = (a[0], b[0])
a.pop(0)
b.pop(0)
cnt = 0
while len(a) > 0 and len(b) > 0 and (cnt < 1000):
	if a[0] > b[0]:
		a.append(b[0])
		a.append(a[0])
	if b[0] > a[0]:
		b.append(a[0])
		b.append(b[0])
	cnt += 1
	a.pop(0)
	b.pop(0)
if len(a) == 0:
	print(cnt, 2)
	quit()
if len(b) == 0:
	print(cnt, 1)
	quit()
if len(a) > 0 and len(b) > 0:
	print(-1)
else:
	print(cnt)


import math, sys
from collections import Counter, defaultdict, deque
from sys import stdin, stdout
input = stdin.readline
lili = lambda : list(map(int, sys.stdin.readlines()))
li = lambda : list(map(int, input().split()))
I = lambda : int(input())
S = lambda : input().strip()
n = I()
a = li()
b = li()
c = deque()
d = deque()
for i in range(1, a[0] + 1):
	c.appendleft(a[i])
for i in range(1, b[0] + 1):
	d.appendleft(b[i])
a = a[1:]
b = b[1:]
t = 0
f = 0
h = defaultdict(list)
while len(c) != 0 and len(d) != 0:
	t += 1
	p = c.pop()
	q = d.pop()
	if t >= 1000:
		f = 1
		break
	if p < q:
		d.appendleft(p)
		d.appendleft(q)
	else:
		c.appendleft(q)
		c.appendleft(p)
if f == 1:
	print(-1)
	exit()
if len(c) == 0:
	print(t, 2)
else:
	print(t, 1)


n = int(input())
(n1, *c1) = list(map(int, input().split()))
(n2, *c2) = list(map(int, input().split()))
from collections import deque
q1 = deque(c1)
q2 = deque(c2)
count = 0
while len(q1) > 0 and len(q2) > 0:
	count += 1
	if count > 99999:
		print('-1')
		exit(0)
	i1 = q1.popleft()
	i2 = q2.popleft()
	if i1 > i2:
		q1.append(i2)
		q1.append(i1)
	else:
		q2.append(i1)
		q2.append(i2)
if len(q1):
	print('%d 1' % count)
else:
	print('%d 2' % count)


n = int(input())
lst1 = list(map(int, input().split()))
k1 = lst1.pop(0)
lst2 = list(map(int, input().split()))
k2 = lst2.pop(0)
cnt = 0
(last1, last2) = (lst1[0], lst2[0])
while 1:
	if len(lst1) == 0 or len(lst2) == 0 or cnt > 10000000.0:
		break
	a = lst1.pop(0)
	b = lst2.pop(0)
	if last1 == b and last2 == a:
		cnt = -1
		break
	last1 = a
	last2 = b
	if a > b:
		lst1.append(b)
		lst1.append(a)
	else:
		lst2.append(a)
		lst2.append(b)
	cnt += 1
if cnt == -1 or cnt > 10000000.0:
	print(-1)
elif len(lst1) == 0:
	print(cnt, 2)
else:
	print(cnt, 1)


n = int(input())
arr1 = [int(i) for i in input().split()]
arr2 = [int(i) for i in input().split()]
n1 = arr1.pop(0)
n2 = arr2.pop(0)
start = [i for i in arr1]
end = [i for i in arr2]
count = 0
flag = 0
while count != 100000:
	if arr1[0] > arr2[0]:
		arr1.append(arr2.pop(0))
		arr1.append(arr1.pop(0))
		n1 += 1
		n2 -= 1
	else:
		arr2.append(arr1.pop(0))
		arr2.append(arr2.pop(0))
		n2 += 1
		n1 -= 1
	count += 1
	if n1 == 0 or n2 == 0:
		if n1 == 0:
			print(count, 2)
		else:
			print(count, 1)
		flag = 1
		break
if flag == 0:
	print(-1)


n = int(input())
ar1 = list(map(int, input().split()))
ar2 = list(map(int, input().split()))
a = ar1[1:]
b = ar2[1:]
newa = a[:]
flag = 1
newb = b[:]
cnt = 0
while len(newa) != 0 or len(newb) != 0:
	if newa[0] > newb[0]:
		t = newa[0]
		newa.remove(newa[0])
		newa.append(newb[0])
		newa.append(t)
		cnt += 1
		newb.remove(newb[0])
	else:
		t = newb[0]
		newb.remove(newb[0])
		newb.append(newa[0])
		newb.append(t)
		cnt += 1
		newa.remove(newa[0])
	if len(newa) == 0:
		z = 2
	if len(newb) == 0:
		z = 1
	if len(newa) == 0 or len(newb) == 0:
		break
	if cnt > 10000:
		flag = 0
		break
if flag == 1:
	print(str(cnt) + ' ' + str(z))
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
log = []
r = 0

def spam(x, y):
	return 2 if not x else 1
while a != [] and b != []:
	r += 1
	l = '{} - {}'.format(str(a), str(b))
	if a[0] > b[0]:
		a.append(b[0])
		a.append(a[0])
		b.remove(b[0])
		a.remove(a[0])
	else:
		b.append(a[0])
		b.append(b[0])
		b.remove(b[0])
		a.remove(a[0])
	if l in log:
		print(-1)
		break
	else:
		log += [l]
else:
	print(r, spam(a, b))


from collections import deque

def main():
	n = int(input())
	s1 = deque(list(map(int, input().split()))[1:])
	s2 = deque(list(map(int, input().split()))[1:])
	move = 0
	ok = True
	while s1 and s2:
		c1 = s1.popleft()
		c2 = s2.popleft()
		if c1 < c2:
			s2.append(c1)
			s2.append(c2)
		elif c2 < c1:
			s1.append(c2)
			s1.append(c1)
		move += 1
		if move >= 100000:
			ok = False
			break
	if ok:
		winner = 1 if not s2 else 2
		print(move, winner)
	else:
		print(-1)
main()


n = int(input())
p1 = list(map(int, input().strip().split(' ')))
p2 = list(map(int, input().strip().split(' ')))
del p1[0]
del p2[0]
player1 = []
player2 = []
k = 0
q = 0
cnt = 0
r = 0
player1.append(p1)
player2.append(p2)
while True:
	q1 = []
	q2 = []
	for i in p1:
		q1.append(i)
	for i in p2:
		q2.append(i)
	if len(p1) == 0:
		k = 1
		break
	if len(p2) == 0:
		q = 1
		break
	if q1[0] > q2[0]:
		w1 = q1[0]
		w2 = q2[0]
		del q2[0]
		del q1[0]
		q1.append(w2)
		q1.append(w1)
	else:
		w1 = q1[0]
		w2 = q2[0]
		del q2[0]
		del q1[0]
		q2.append(w1)
		q2.append(w2)
	if q1 in player1 and q2 in player2:
		r = 1
		break
	else:
		p1 = [0 for i in range(len(q1))]
		p2 = [0 for i in range(len(q2))]
		for i in range(len(q1)):
			p1[i] = q1[i]
		for i in range(len(q2)):
			p2[i] = q2[i]
		player1.append(p1)
		player2.append(p2)
	cnt += 1
if r == 1:
	print(-1)
elif k == 1:
	print(cnt, '2')
else:
	print(cnt, '1')


n = int(input())
from collections import deque
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
a = deque(a)
b = deque(b)
import copy
c = a.copy()
d = b.copy()
(l, r) = (0, 0)
while len(a) != 0 and len(b) != 0:
	p = a.popleft()
	q = b.popleft()
	if p > q:
		a.append(q)
		a.append(p)
	else:
		b.append(p)
		b.append(q)
	l += 1
	if c == a and d == b or l >= 100000:
		r = r + 1
		break
if r == 0:
	print(l, end=' ')
	if len(b) > 0:
		print(2)
	else:
		print(1)
else:
	print(-1)


nos = int(input())
player1 = set([])
player2 = set([])
dec1 = [int(x) for x in input().split()][1:]
dec2 = [int(x) for x in input().split()][1:]
count = 0
while dec1 and dec2:
	card1 = dec1.pop(0)
	card2 = dec2.pop(0)
	if card1 > card2:
		dec1.append(card2)
		dec1.append(card1)
	else:
		dec2.append(card1)
		dec2.append(card2)
	count += 1
	t2 = tuple(dec2)
	t1 = tuple(dec1)
	if t1 in player1 and t2 in player2:
		print(-1)
		break
	else:
		player1.add(t1)
		player2.add(t2)
else:
	print(count, 1 if dec1 else 2)


n = int(input())
b1 = list(map(int, input().split()))
k1 = b1.pop(0)
b2 = list(map(int, input().split()))
k2 = b2.pop(0)
for i in range(1, 120):
	t1 = b1.pop(0)
	t2 = b2.pop(0)
	if t1 > t2:
		b1.extend([t2, t1])
	else:
		b2.extend([t1, t2])
	if [] == b1:
		print(i, 2)
		break
	elif [] == b2:
		print(i, 1)
		break
else:
	print(-1)


def comp(a, b):
	if len(a) != len(b):
		return False
	n = len(a)
	for i in range(n):
		if a[i] != b[i]:
			return False
	return True
n = int(input())
a = []
b = []
a = list(map(int, input().split()))
b = list(map(int, input().split()))
k1 = a[0]
k2 = b[0]
del a[0]
del b[0]
p = []
q = []
for i in a:
	p.append(i)
for i in b:
	q.append(i)
total = 0
flag = True
while True:
	x = a[0]
	y = b[0]
	if x > y:
		a.pop(0)
		b.pop(0)
		a.append(y)
		a.append(x)
	else:
		a.pop(0)
		b.pop(0)
		b.append(x)
		b.append(y)
	total += 1
	if p == a and q == b or total >= 100000:
		flag = False
		break
	if len(a) == 0 or len(b) == 0:
		break
if flag == False:
	print(-1)
elif a == []:
	print(total, 2)
else:
	print(total, 1)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy
from itertools import chain, dropwhile, permutations, combinations
from collections import defaultdict, deque

def VI():
	return list(map(int, input().split()))

def I():
	return int(input())

def LIST(n, m=None):
	return [0] * n if m is None else [[0] * m for i in range(n)]

def ELIST(n):
	return [[] for i in range(n)]

def MI(n=None, m=None):
	if n is None:
		(n, m) = VI()
	arr = LIST(n)
	for i in range(n):
		arr[i] = VI()
	return arr

def MS(n=None, m=None):
	if n is None:
		(n, m) = VI()
	arr = LIST(n)
	for i in range(n):
		arr[i] = input()
	return arr

def MIT(n=None, m=None):
	if n is None:
		(n, m) = VI()
	a = MI(n, m)
	arr = LIST(m, n)
	for (i, l) in enumerate(a):
		for (j, x) in enumerate(l):
			arr[j][i] = x
	return arr

def run(n, k1, k2, a, b):
	p = deque(a)
	q = deque(b)
	for i in range(2 * n ** 2):
		if len(p) == 0 or len(q) == 0:
			print(i, [1, 2][len(p) == 0])
			return
		x = p.popleft()
		y = q.popleft()
		if x > y:
			p.append(y)
			p.append(x)
		else:
			q.append(x)
			q.append(y)
	print(-1)

def main(info=0):
	n = I()
	(k1, *a) = VI()
	(k2, *b) = VI()
	run(n, k1, k2, a, b)
main()


def to_int(lis):
	for i in range(len(lis)):
		lis[i] = int(lis[i])
	return lis
n = int(input())
p1 = input().split()
p2 = input().split()
p1.pop(0)
p2.pop(0)
p1 = to_int(p1)
p2 = to_int(p2)
set1 = [p1.copy()]
set2 = [p2.copy()]
f = 0
e = 1
while 1:
	if len(p1) == 0:
		print(f, end=' ')
		print(2)
		break
	elif len(p2) == 0:
		print(f, end=' ')
		print(1)
		break
	else:
		f += 1
		n1 = p1[0]
		n2 = p2[0]
		p1.pop(0)
		p2.pop(0)
		if n1 > n2:
			p1.append(n2)
			p1.append(n1)
		else:
			p2.append(n1)
			p2.append(n2)
	for i in range(len(set1)):
		if p1 == set1[i] and p2 == set2[i] and (f != 0):
			print(-1)
			e = 0
			break
	if e == 0:
		break
	set1.append(p1.copy())
	set2.append(p2.copy())


def main():
	trash = input()
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	qa = a[1:]
	qb = b[1:]
	ctr = 0
	while ctr < 10 ** 6:
		if len(qa) == 0:
			print(ctr, 2)
			return
		elif len(qb) == 0:
			print(ctr, 1)
			return
		if qa[0] > qb[0]:
			qa.append(qb[0])
			qa.append(qa[0])
			del qa[0]
			del qb[0]
		elif qb[0] > qa[0]:
			qb.append(qa[0])
			qb.append(qb[0])
			del qa[0]
			del qb[0]
		else:
			break
		ctr += 1
	print(-1)
main()


import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
ll1 = deque(map(int, input().split()))
ll2 = deque(map(int, input().split()))
s1 = ll1[0]
s2 = ll2[0]
ll1.popleft()
ll2.popleft()
l1 = deque(ll1)
l2 = deque(ll2)
cou = 0
lol = 0
while len(l1) != 0 and len(l2) != 0:
	if l1[0] > l2[0]:
		l1.append(l2.popleft())
		l1.append(l1.popleft())
	else:
		l2.append(l1.popleft())
		l2.append(l2.popleft())
	cou += 1
	f1 = 0
	f2 = 0
	if len(l1) == s1:
		for i in range(s1):
			if ll1[i] != l1[i]:
				f1 = 1
				break
	else:
		f1 = 1
	if len(l2) == s2:
		for i in range(s2):
			if ll2[i] != l2[i]:
				f2 = 1
				break
	else:
		f2 = 1
	if f1 == 0 and f2 == 0:
		lol = 1
		break
	if cou == 100000:
		break
if len(l1) == 0:
	print(cou, 2)
elif len(l2) == 0:
	print(cou, 1)
else:
	print(-1)


kart = input()
player_1 = input()
player_2 = input()
kart_1 = []
kart_2 = []
kart_save = []
kart_save_2 = []
i = 0
while i < len(player_1):
	if i > 0:
		if player_1[i] != ' ':
			if i < len(player_1) - 1:
				if player_1[i + 1] != ' ':
					tmp = player_1[i] + player_1[i + 1]
					kart_1.append(int(tmp))
					i = i + 1
				else:
					kart_1.append(int(player_1[i]))
			else:
				kart_1.append(int(player_1[i]))
	i = i + 1
i = 0
while i < len(player_2):
	if i > 0:
		if player_2[i] != ' ':
			if i < len(player_2) - 1:
				if player_2[i + 1] != ' ':
					tmp = player_2[i] + player_2[i + 1]
					kart_2.append(int(tmp))
					i = i + 1
				else:
					kart_2.append(int(player_2[i]))
			else:
				kart_2.append(int(player_2[i]))
	i = i + 1
counter = 0
if kart_1.count(int(kart)) == 1:
	for i in kart_1:
		kart_save.append(i)
	for i in kart_2:
		kart_save_2.append(i)
	while len(kart_1) < int(kart):
		if kart_1[0] > kart_2[0]:
			tmp = kart_2.pop(0)
			kart_1.append(tmp)
			tmp = kart_1.pop(0)
			kart_1.append(tmp)
		else:
			tmp = kart_1.pop(0)
			kart_2.append(tmp)
			tmp = kart_2.pop(0)
			kart_2.append(tmp)
		counter = counter + 1
		if kart_1 == kart_save and kart_2 == kart_save_2 or counter > 100000:
			print('-1')
			break
	if len(kart_1) == int(kart):
		print(counter, 1)
else:
	for i in kart_1:
		kart_save.append(i)
	for i in kart_2:
		kart_save_2.append(i)
	while len(kart_2) < int(kart):
		if kart_1[0] > kart_2[0]:
			tmp = kart_2.pop(0)
			kart_1.append(tmp)
			tmp = kart_1.pop(0)
			kart_1.append(tmp)
		else:
			tmp = kart_1.pop(0)
			kart_2.append(tmp)
			tmp = kart_2.pop(0)
			kart_2.append(tmp)
		counter = counter + 1
		if kart_1 == kart_save and kart_2 == kart_save_2 or counter > 100000:
			print('-1')
			break
	if len(kart_2) == int(kart):
		print(counter, 2)


n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
(l1, l2) = (l1[1:], l2[1:])
(temp, count, poppp) = ([], 0, 0)
while 1:
	if count > 200:
		poppp = 1
		break
	elif l1[0] == l2[0]:
		poppp = 1
		break
	else:
		if l1[0] > l2[0]:
			l1.append(l2[0])
			l1.append(l1[0])
			l1.pop(0)
			l2.pop(0)
		else:
			l2.append(l1[0])
			l2.append(l2[0])
			l1.pop(0)
			l2.pop(0)
		count += 1
	if len(l1) == 0:
		winner = 2
		break
	if len(l2) == 0:
		winner = 1
		break
if poppp:
	print(-1)
else:
	print(count, winner)


n = int(input())
s1 = [int(card) for card in input().split()]
s2 = [int(card) for card in input().split()]
s1 = s1[1:]
s2 = s2[1:]
magic = 1000000
fights = 0
flag = False
while True:
	(card1, card2) = (s1.pop(0), s2.pop(0))
	fights += 1
	if fights > magic:
		flag = True
		break
	if card1 > card2:
		s1.append(card2)
		s1.append(card1)
	else:
		s2.append(card1)
		s2.append(card2)
	if s1 == []:
		winner = 2
		break
	if s2 == []:
		winner = 1
		break
if flag:
	print(-1)
else:
	print(fights, winner)


n = int(input())
c1 = list(map(int, input().split()))[1:]
c2 = list(map(int, input().split()))[1:]
res = 0
while c1 and c2:
	if res > 1000:
		print(-1)
		exit()
	res = res + 1
	(x, y) = (c1.pop(0), c2.pop(0))
	if x > y:
		c1 += [y, x]
	else:
		c2 += [x, y]
if c1:
	print(res, 1)
else:
	print(res, 2)


n = int(input())
s = input()
li = list(map(int, s.split()))
s = input()
li2 = list(map(int, s.split()))
li.pop(0)
li2.pop(0)
nn = 1
for i in range(n):
	nn *= i + 1
cnt = 0
for i in range(nn):
	sz = len(li)
	sz2 = len(li2)
	if sz == 0:
		print(cnt, 2)
		exit()
	elif sz2 == 0:
		print(cnt, 1)
		exit()
	cnt += 1
	x = li[0]
	x2 = li2[0]
	if x > x2:
		li.pop(0)
		li.append(x2)
		li.append(x)
		li2.pop(0)
	else:
		li2.pop(0)
		li2.append(x)
		li2.append(x2)
		li.pop(0)
print(-1)


mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
n = ii()
(k1, *l1) = f()
(k2, *l2) = f()
ld1 = l1[:]
ld2 = l2[:]
ans = 0
while 1:
	if ld1[0] < ld2[0]:
		ld2.append(ld1[0])
		ld2.append(ld2[0])
		ld1.pop(0)
		ld2.pop(0)
	else:
		ld1.append(ld2[0])
		ld1.append(ld1[0])
		ld1.pop(0)
		ld2.pop(0)
	ans += 1
	if ld1 == []:
		print(ans, 2)
		exit(0)
	elif ld2 == []:
		print(ans, 1)
		exit(0)
	elif ans > 10000:
		print(-1)
		exit()


n = list(map(int, input().split()))
l_1 = list(map(int, input().split()))[1:]
l_2 = list(map(int, input().split()))[1:]
l_1c = l_1.copy()
l_2c = l_2.copy()
t = 0
while len(l_1c) != 0 and len(l_2c) != 0:
	if l_1c[0] == l_2c[0]:
		l_1c.append(l_1c[0])
		l_2c.append(l_2c[0])
	elif l_1c[0] > l_2c[0]:
		l_1c.append(l_2c[0])
		l_1c.append(l_1c[0])
	else:
		l_2c.append(l_1c[0])
		l_2c.append(l_2c[0])
	del l_1c[0]
	del l_2c[0]
	t += 1
	if t > 10000:
		print(-1)
		quit()
print('%d %d' % (t, 2 if len(l_1c) == 0 else 1))


n = int(input())
c1 = list(map(int, input().split()))[1:]
c2 = list(map(int, input().split()))[1:]

def check(c1, c2):
	(t1, t2) = (c1.pop(0), c2.pop(0))
	if t1 < t2:
		c2 += [t1, t2]
	else:
		c1 += [t2, t1]
count = 0
while c1 != [] and c2 != []:
	(prev_c1, prev_c2) = (c1[:], c2[:])
	check(c1, c2)
	if count > 10000:
		break
	count += 1
else:
	print(count, 2 if c1 == [] else 1)
	quit()
print(-1)


__author__ = 'trunghieu11'
n = int(input())
first = list(map(int, input().split()))[1:]
second = list(map(int, input().split()))[1:]
first.reverse()
second.reverse()
round = 0
while round < 10000:
	if len(first) * len(second) == 0:
		break
	fCard = first.pop()
	sCard = second.pop()
	if fCard > sCard:
		first.insert(0, sCard)
		first.insert(0, fCard)
	else:
		second.insert(0, fCard)
		second.insert(0, sCard)
	round += 1
if len(first) == 0:
	print(round, 2)
elif len(second) == 0:
	print(round, 1)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split(' ')))
k = a.pop(0)
b = list(map(int, input().split(' ')))
k1 = b.pop(0)
total = 0
s = 1
while len(a) > 0 and len(b) > 0:
	if a[0] > b[0]:
		total = total + 1
		a.append(b[0])
		b.pop(0)
		c = a.pop(0)
		a.append(c)
	else:
		total = total + 1
		b.append(a[0])
		a.pop(0)
		c = b.pop(0)
		b.append(c)
	if total > 5000:
		s = 0
		break
if s == 0:
	print('-1')
elif len(a) > len(b):
	print(total, '1')
else:
	print(total, '2')


import sys
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
b = list(map(int, sys.stdin.readline().split()))
kone = a[0]
a.pop(0)
ktwo = b[0]
b.pop(0)
rec = []
rec.append((a.copy(), b.copy()))
count = 0
repeat = False
while len(a) != 0 and len(b) != 0:
	atemp = a.pop(0)
	btemp = b.pop(0)
	if atemp > btemp:
		a.append(btemp)
		a.append(atemp)
	else:
		b.append(atemp)
		b.append(btemp)
	temp = (a.copy(), b.copy())
	if temp in rec:
		repeat = True
		print(-1)
		break
	else:
		rec.append(temp)
		count += 1
if not repeat:
	res = 1 if len(b) == 0 else 2
	print(str(count) + ' ' + str(res))


nCards = int(input())
(n1Cards, *cards1) = [int(x) for x in input().split()]
(n2Cards, *cards2) = [int(x) for x in input().split()]
top1 = 0
top2 = 0
end1 = n1Cards
end2 = n2Cards
seenStates = set((tuple(sum([cards1, [0], cards2], [])),))
turns = 0
while top1 != end1 and top2 != end2:
	if cards1[top1] > cards2[top2]:
		cards1.append(cards2[top2])
		cards1.append(cards1[top1])
		top1 += 1
		top2 += 1
		end1 += 2
	else:
		cards2.append(cards1[top1])
		cards2.append(cards2[top2])
		top1 += 1
		top2 += 1
		end2 += 2
	if (tuple(sum([cards1[top1:end1 + 1], [0], cards2[top2:end2 + 1]], [])),) in seenStates:
		print(-1)
		break
	seenStates.add((tuple(sum([cards1[top1:end1 + 1], [0], cards2[top2:end2 + 1]], [])),))
	turns += 1
else:
	if top1 == end1:
		print(turns, 2)
	else:
		print(turns, 1)


from collections import deque
n = int(input())
a = deque([int(i) for i in input().split()[1:]])
b = deque([int(i) for i in input().split()[1:]])
ans = 0
while a and b:
	ans += 1
	if ans > 1000000:
		print(-1)
		exit()
	aa = a.popleft()
	bb = b.popleft()
	if aa > bb:
		a.append(bb)
		a.append(aa)
	else:
		b.append(aa)
		b.append(bb)
if a:
	print(ans, 1)
else:
	print(ans, 2)


import copy
cartas = int(input())
p1 = list(map(int, input().split(' ')))[1:]
p2 = list(map(int, input().split(' ')))[1:]
cont = 0
estados = []
while True:
	p1t = copy.copy(p1)
	p2t = copy.copy(p2)
	estados.append([p1t, p2t])
	if p1 == []:
		print('{} 2'.format(cont))
		break
	if p2 == []:
		print('{} 1'.format(cont))
		break
	if p1[0] > p2[0]:
		cont += 1
		p1.append(p2.pop(0))
		p1.append(p1.pop(0))
	else:
		cont += 1
		p2.append(p1.pop(0))
		p2.append(p2.pop(0))
	p = [p1, p2]
	if p in estados:
		print(-1)
		break


class Gamer:

	def __init__(self):
		self.cards = []

	def play_card(self):
		if not self.cards:
			return False
		return self.cards.pop(0)

	def win_round(self, *cards):
		self.cards.extend(cards)

def game_round(gamer_a, gamer_b):
	card_a = gamer_a.play_card()
	card_b = gamer_b.play_card()
	if card_a > card_b:
		gamer_a.win_round(card_b, card_a)
		if not gamer_b.cards:
			return 1
		return False
	if card_a < card_b:
		gamer_b.win_round(card_a, card_b)
		if not gamer_a.cards:
			return 2
		return False

def game(gamer_a, gamer_b, c_q):
	count = 1
	for i in range(106):
		x = game_round(gamer_a, gamer_b)
		if x:
			print(count, x, sep=' ')
			break
		count += 1
	else:
		print(-1)
soldier1 = Gamer()
soldier2 = Gamer()
cards_quantity = int(input().rstrip())
card_set1 = list(map(int, input().split()))
card_set2 = list(map(int, input().split()))
soldier1.win_round(*card_set1[1:])
soldier2.win_round(*card_set2[1:])
game(soldier1, soldier2, cards_quantity)


n = int(input())
l1 = list(map(int, input().strip().split()))
l2 = list(map(int, input().strip().split()))
k1 = l1.pop(0)
k2 = l2.pop(0)
state = []
f = 0
while True:
	if [l1, l2] in state:
		print(-1)
		break
	else:
		state.append([[k for k in l1], [i for i in l2]])
	if l1 == []:
		print(f, 2)
		break
	if l2 == []:
		print(f, 1)
		break
	f += 1
	if l1[0] > l2[0]:
		l1.append(l2.pop(0))
		l1.append(l1.pop(0))
	else:
		l2.append(l1.pop(0))
		l2.append(l2.pop(0))


from collections import deque
n = int(input())
player1 = [int(x) for x in input().split()]
player2 = [int(x) for x in input().split()]
player1Cards = deque([])
player2Cards = deque([])
for i in range(1, player1[0] + 1):
	player1Cards.append(player1[i])
for i in range(1, player2[0] + 1):
	player2Cards.append(player2[i])
itera = 0
a = True
while itera < n * 50:
	card1 = player1Cards.popleft()
	card2 = player2Cards.popleft()
	if card1 > card2:
		player1Cards.append(card2)
		player1Cards.append(card1)
		if len(player2Cards) == 0:
			print(str(itera + 1) + ' ' + str(1))
			a = False
			break
	else:
		player2Cards.append(card1)
		player2Cards.append(card2)
		if len(player1Cards) == 0:
			print(str(itera + 1) + ' ' + str(2))
			a = False
			break
	itera += 1
if a:
	print(str(-1))


n = int(input())
(k1, *l1) = map(int, input().split())
(k2, *l2) = map(int, input().split())
l = [l1, l2]
r = []
c = 0
while 1:
	if l[0] == []:
		print(c, end=' ')
		print(2)
		break
	elif l[1] == []:
		print(c, end=' ')
		print(1)
		break
	else:
		b = l[0][0] > l[1][0]
		if b:
			l[0].append(l[1][0])
			l[0].append(l[0][0])
			l[1].pop(0)
			l[0].pop(0)
			lr = list(map(str, l))
			a = ''.join(lr[:][0]) + ':' + ''.join(lr[:][1])
			if a in r:
				print(-1)
				break
			r.append(a)
			c += 1
		else:
			l[1].append(l[0][0])
			l[1].append(l[1][0])
			l[0].pop(0)
			l[1].pop(0)
			lr = list(map(str, l))
			a = ''.join(lr[:][0]) + ':' + ''.join(lr[:][1])
			if a in r:
				print(-1)
				break
			r.append(a)
			c += 1


n = int(input())
a = [int(c) for c in input().split()]
b = [int(c) for c in input().split()]
del a[0]
del b[0]
dict = set()
moves = 0
while True:
	if len(a) == 0 or len(b) == 0 or ''.join((str(e) for e in a)) + '.' + ''.join((str(e) for e in b)) in dict:
		break
	dict.add(''.join((str(e) for e in a)) + '.' + ''.join((str(e) for e in b)))
	winner = []
	looser = []
	if a[0] > b[0]:
		winner = a
		looser = b
	else:
		winner = b
		looser = a
	winner.append(looser[0])
	winner.append(winner[0])
	del winner[0]
	del looser[0]
	moves += 1
if len(a) == 0:
	print('%d 2' % moves)
elif len(b) == 0:
	print('%d 1' % moves)
else:
	print('-1')


n = int(input())
l = list(map(int, input().split()))
l1 = list(map(int, input().split()))
k = 0
del l[0]
del l1[0]
c = 1
v = []
v1 = []
v.append(str(l))
v1.append(str(l1))
while len(l) != 0 and len(l1) != 0:
	p = l[0]
	p1 = l1[0]
	del l[0]
	del l1[0]
	if p > p1:
		l.append(p1)
		l.append(p)
	if p < p1:
		l1.append(p)
		l1.append(p1)
	if p == p1:
		l.append(p)
		l1.append(p)
	if str(l) in v and str(l1) in v1:
		c = 0
		break
	v.append(str(l))
	v1.append(str(l1))
	k = k + 1
if c == 0:
	print(-1)
else:
	g = []
	if len(l) > len(l1):
		g.append(1)
	else:
		g.append(2)
	print(k, *g)


import sys
n = int(input())
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
k1 = arr1[0]
k2 = arr2[0]
arr1 = arr1[1:]
arr2 = arr2[1:]
iterx = 0
while iterx < 2000:
	if len(arr1) == 0:
		print(iterx, 2, sep=' ')
		sys.exit()
	if len(arr2) == 0:
		print(iterx, 1, sep=' ')
		sys.exit()
	if arr1[0] > arr2[0]:
		arr1 = arr1 + [arr2[0], arr1[0]]
		arr2 = arr2[1:]
		arr1 = arr1[1:]
	else:
		arr2 = arr2 + [arr1[0], arr2[0]]
		arr1 = arr1[1:]
		arr2 = arr2[1:]
	iterx += 1
print(-1)


import time
x = input()
numberCards = int(x)
cardsPlayer1 = [int(i) for i in input().split()]
cardsPlayer2 = [int(i) for i in input().split()]
numberCardsPlayer1 = cardsPlayer1.pop(0)
numberCardsPlayer2 = cardsPlayer2.pop(0)
originalCardsPlayer1 = []
originalCardsPlayer2 = []
numberBattles = 0
gamePossible = True
while 1:
	originalCardsPlayer1.append(list(cardsPlayer1))
	originalCardsPlayer2.append(list(cardsPlayer2))
	if len(cardsPlayer1) == 0 or len(cardsPlayer2) == 0:
		break
	numberBattles += 1
	element1 = cardsPlayer1.pop(0)
	element2 = cardsPlayer2.pop(0)
	if element2 > element1:
		cardsPlayer2.append(element1)
		cardsPlayer2.append(element2)
	else:
		cardsPlayer1.append(element2)
		cardsPlayer1.append(element1)
	if cardsPlayer1 in originalCardsPlayer1 and cardsPlayer2 in originalCardsPlayer2:
		gamePossible = False
		break
if gamePossible == True:
	if len(cardsPlayer1) == 0:
		print(numberBattles, 2)
	else:
		print(numberBattles, 1)
else:
	print(-1)


import sys
input = sys.stdin.readline
from collections import deque
x = int(input())
(*li1,) = map(int, input().split())
(*li2,) = map(int, input().split())
(a, b) = (li1[0], li2[0])
cnt = 0
li1 = deque(li1[1:])
li2 = deque(li2[1:])
while cnt < 1000:
	c = li1.popleft()
	d = li2.popleft()
	if c > d:
		li1 += [d, c]
	else:
		li2 += [c, d]
	cnt += 1
	if len(li1) == 0 or len(li2) == 0:
		print(cnt, 1 if len(li2) == 0 else 2)
		break
else:
	print(-1)


def top(a, b):
	if a > b:
		return 1
	if b > a:
		return 2
cc = int(input())
p1 = list(map(int, input().split()))
p2 = list(map(int, input().split()))
game = 1
tie = []
f = 0
log = {}
check = 0
g = []
while game == 1:
	d = top(p1[1], p2[1])
	if d == 1:
		p1.append(p2[1])
		p2.pop(1)
		p1.append(p1[1])
		p1.pop(1)
		f += 1
	elif d == 2:
		p2.append(p1[1])
		p1.pop(1)
		p2.append(p2[1])
		p2.pop(1)
		f += 1
	if len(p1) == 1:
		winner = 2
		game = 0
	if len(p2) == 1:
		winner = 1
		game = 0
	if f > 20:
		if p1[1:] not in g:
			g.append(p1[1:])
		e = g.index(p1[1:])
		log[e] = log.get(e, 0) + 1
		if log[e] == 10:
			winner = 0
			game = 0
if winner > 0:
	print(str(f) + ' ' + str(winner))
if winner == 0:
	print(-1)


from collections import deque
n = int(input())
d = set()
(k1, *a) = [int(s) for s in input().split()]
(k2, *b) = [int(s) for s in input().split()]
a = deque(a)
b = deque(b)
res = 0
while a and b:
	cu = tuple([tuple(a), tuple(b)])
	if not cu in d:
		d.add(cu)
		res += 1
		cur1 = a.popleft()
		cur2 = b.popleft()
		if cur1 > cur2:
			a.append(cur2)
			a.append(cur1)
		else:
			b.append(cur1)
			b.append(cur2)
	else:
		print(-1)
		break
else:
	if len(a) > len(b):
		print(res, 1)
	else:
		print(res, 2)


__author__ = 'Andrey'
import collections
import time
start = time.time()
n = int(input())
cards_1 = collections.deque(list(map(int, input().split()))[1:])
cards_2 = collections.deque(list(map(int, input().split()))[1:])
c = 0
bad = False
while cards_1 and cards_2:
	end = time.time()
	if end - start > 1.85:
		bad = True
		break
	n_1 = cards_1.popleft()
	n_2 = cards_2.popleft()
	c += 1
	if n_1 > n_2:
		cards_1.append(n_2)
		cards_1.append(n_1)
	else:
		cards_2.append(n_1)
		cards_2.append(n_2)
else:
	print(c, 1 if cards_1 else 2)
if bad:
	print(-1)


from collections import deque
n = int(input())
A = deque(list(map(int, input().split())))
B = deque(list(map(int, input().split())))
A.popleft()
B.popleft()
for i in range(3 * 10 ** 6):
	if len(A) == 0:
		print(i, 2)
		exit(0)
	elif len(B) == 0:
		print(i, 1)
		exit(0)
	else:
		x = A.popleft()
		y = B.popleft()
		if x > y:
			A.append(y)
			A.append(x)
		else:
			B.append(x)
			B.append(y)
print(-1)


from collections import deque
n = int(input())
A = [int(i) for i in input().split()][1:]
B = [int(i) for i in input().split()][1:]
A = deque(A)
B = deque(B)
res = 0
states = {}
states[tuple(A), tuple(B)] = 1
while len(A) and len(B):
	res += 1
	if A[0] > B[0]:
		A.extend([B[0], A[0]])
	else:
		B.extend([A[0], B[0]])
	A.popleft()
	B.popleft()
	if (tuple(A), tuple(B)) in states:
		print(-1)
		exit()
	states[tuple(A), tuple(B)] = 1
print(res, 1 + (len(A) == 0))


n = int(input())
k1 = list(map(int, input().split()[1:]))
k2 = list(map(int, input().split()[1:]))
i = 0
while True:
	if len(k1) == 0 or len(k2) == 0:
		break
	if i > 10000:
		break
	if k1[0] > k2[0]:
		k1 = k1[1:] + k2[0:1] + k1[0:1]
		k2 = k2[1:]
	else:
		k2 = k2[1:] + k1[0:1] + k2[0:1]
		k1 = k1[1:]
	i += 1
if i > 10000:
	print(-1)
else:
	winner = 1
	if len(k1) == 0:
		winner = 2
	print(i, winner)


from collections import deque
n = int(input())
p1 = list(map(int, input().split()))
p2 = list(map(int, input().split()))
q1 = deque(p1[1:])
q2 = deque(p2[1:])
i = 0
while i <= n * n + n and q1 and q2:
	c1 = q1.popleft()
	c2 = q2.popleft()
	if c1 > c2:
		q1.append(c2)
		q1.append(c1)
	else:
		q2.append(c1)
		q2.append(c2)
	i += 1
if q1 and q2:
	print(-1)
else:
	winner = 1
	if q2:
		winner = 2
	print(i, winner)


n = int(input())
s1 = [int(i) for i in input().split()]
s1.pop(0)
s2 = [int(i) for i in input().split()]
s2.pop(0)
t = 0
while s1 and s2:
	t += 1
	a = s1.pop(0)
	b = s2.pop(0)
	if a > b:
		s1.append(b)
		s1.append(a)
	else:
		s2.append(a)
		s2.append(b)
	if t > 1000:
		break
if t > 1000:
	print(-1)
elif s1:
	print(t, 1)
else:
	print(t, 2)


import copy
n = int(input())
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))
(k1, k2) = (s1.pop(0), s2.pop(0))
s11 = copy.deepcopy(s1)
s22 = copy.deepcopy(s2)
cnt = 0
while True:
	cnt += 1
	(a, b) = (s11.pop(0), s22.pop(0))
	if a > b:
		s11.append(b)
		s11.append(a)
	else:
		s22.append(a)
		s22.append(b)
	if s11 == s1 and s22 == s2:
		print(-1)
		break
	if len(s11) == 0:
		print(cnt, 2)
		break
	if len(s22) == 0:
		print(cnt, 1)
		break
	if cnt > 10000:
		print(-1)
		break


from collections import deque
n = int(input())
first = deque(map(int, input().split()[1:]))
second = deque(map(int, input().split()[1:]))
cnt = 0
while first and second:
	p = first.popleft()
	q = second.popleft()
	if p > q:
		first.extend([q, p])
	else:
		second.extend([p, q])
	cnt += 1
	if cnt > 10 ** 3:
		print(-1)
		exit(0)
print(cnt, 1 if first else 2)


def main():
	n = input()
	first = [int(x) for x in input().split()][1:]
	sec = [int(x) for x in input().split()][1:]
	temp_first = first
	temp_sec = sec
	counter = 0
	while True:
		if len(first) > 0 and len(sec) > 0:
			if counter > 99999:
				return -1
			else:
				if first[0] > sec[0]:
					first = first[1:] + [sec[0], first[0]]
					sec = sec[1:]
				else:
					sec = sec[1:] + [first[0], sec[0]]
					first = first[1:]
				counter += 1
		else:
			return str(counter) + ' ' + str(2 ** (len(sec) > 0))
print(main())


from collections import deque
from math import factorial
n = int(input())
k = list(map(int, input().split()))
k1 = k[0]
q1 = deque(k[1:])
k = list(map(int, input().split()))
k2 = k[0]
q2 = deque(k[1:])
win = 0
max = factorial(n)
cur = 0
done = set()
while cur < max:
	if not q1:
		win = 2
		break
	if not q2:
		win = 1
		break
	s1 = ''.join((str(i) for i in q1))
	s2 = ''.join((str(i) for i in q2))
	if s1 in done and s2 in done:
		break
	done.add(s1)
	done.add(s2)
	cur += 1
	c1 = q1.popleft()
	c2 = q2.popleft()
	if c1 > c2:
		q1.append(c2)
		q1.append(c1)
	else:
		q2.append(c1)
		q2.append(c2)
if win == 0:
	print(-1)
else:
	print(cur, win)


from collections import deque
p1 = p2 = deque()
mp = dict()
ans = 0
winner = 0

def generate():
	global p1, p2, ans, winner
	if len(p1) == 0:
		winner = 2
		return
	elif len(p2) == 0:
		winner = 1
		return
	if mp.get(str(p1)) == str(p2) or mp.get(str(p2)) == str(p1):
		ans = -1
		return
	mp[str(p1)] = str(p2)
	a = p1.popleft()
	b = p2.popleft()
	ans += 1
	if a > b:
		p1.append(b)
		p1.append(a)
	else:
		p2.append(a)
		p2.append(b)
	generate()

def main():
	global p1, p2, mp, ans
	mp[str([-1])] = [-1]
	m = input()
	p1 = deque((int(x) for x in input().split()))
	nump1 = p1.popleft()
	p2 = deque((int(x) for x in input().split()))
	nump2 = p2.popleft()
	generate()
	if winner != 0:
		print(str(ans) + ' ' + str(winner))
	else:
		print(-1)
main()


n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
count = 0
visited = {tuple(a): True, tuple(b): True}
while a and b:
	c = a.pop(0)
	d = b.pop(0)
	if c > d:
		a.append(d)
		a.append(c)
	else:
		b.append(c)
		b.append(d)
	count += 1
	(ta, tb) = (tuple(a), tuple(b))
	if visited.get(ta) == None:
		visited[ta] = True
	elif visited.get(tb) == None:
		visited[tb] = True
	else:
		print(-1)
		break
else:
	print(count, [1, 2][len(a) == 0])


n = int(input())
f_deck = list(map(int, input().split(' ')))[1:]
s_deck = list(map(int, input().split(' ')))[1:]
idx = 0
rec = []
while 1:
	rec.append(''.join(list(map(str, f_deck))) + '_' + ''.join(list(map(str, s_deck))))
	if f_deck[0] > s_deck[0]:
		f_deck.append(s_deck.pop(0))
		f_deck.append(f_deck.pop(0))
	else:
		s_deck.append(f_deck.pop(0))
		s_deck.append(s_deck.pop(0))
	idx += 1
	if ''.join(list(map(str, f_deck))) + '_' + ''.join(list(map(str, s_deck))) in rec:
		break
	if len(f_deck) == 0 or len(s_deck) == 0:
		break
if len(f_deck) == 0:
	print('{} {}'.format(idx, 2))
elif len(s_deck) == 0:
	print('{} {}'.format(idx, 1))
else:
	print(-1)


from collections import deque
n = int(input())
c1 = [int(v) for v in input().split()]
c2 = [int(v) for v in input().split()]
p1 = deque(c1[1:])
p2 = deque(c2[1:])
vis = set()
fround = 0
while len(p1) > 0 and len(p2) > 0 and (str(p1) + str(p2) not in vis):
	vis.add(str(p1) + str(p2))
	u = p1.popleft()
	v = p2.popleft()
	if u > v:
		p1.extend([v, u])
	else:
		p2.extend([u, v])
	fround += 1
if len(p1) == 0 or len(p2) == 0:
	print(fround, 1 if len(p2) == 0 else 2)
else:
	print(-1)


n = int(input())
p1 = list(map(int, input().split()))
p1 = p1[1:]
p2 = list(map(int, input().split()))
p2 = p2[1:]
for i in range(1000000):
	p1_card = p1.pop(0)
	p2_card = p2.pop(0)
	if p1_card > p2_card:
		p1 += [p2_card, p1_card]
	elif p2_card > p1_card:
		p2 += [p1_card, p2_card]
	if len(p1) == 0:
		print(f'{i + 1} 2')
		exit()
	elif len(p2) == 0:
		print(f'{i + 1} 1')
		exit()
print(-1)