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.

First line contains a single integer n (2 ≤ n ≤ 10), the number of cards. Second line contains integer k1 (1 ≤ k1 ≤ n - 1), the number of the first soldier's cards. Then follow k1 integers that are the values on the first soldier's cards, from top to bottom of his stack. Third line contains integer k2 (k1 + k2 = n), the number of the second soldier's cards. Then follow k2 integers that are the values on the second soldier's cards, from top to bottom of his stack. All card values are different.

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.

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)

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)

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 = [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)

##############--->>>>> Deepcoder Amit Kumar Bhuyan <<<<<---##############

"""
 Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
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()

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import log,sqrt,factorial,cos,tan,sin,radians
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *
#import threading
#from itertools import permutations
#Copy 2D list  m = [x[:] for x in mark] .. Avoid Using Deepcopy
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())
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;

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

# swap_array function
def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;

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

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

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

## nCr function efficient using Binomial Cofficient
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)

## upper bound function code -- such that e in a[:i] e < x;

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    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
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

## MODULAR EXPONENTIATION FUNCTION
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

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b;

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
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;

# the union function which makes union(x,y)
# of two nodes x and y
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

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
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

# Euler's Toitent Function phi
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

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 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;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
spf = [0 for i in range(MAXN)]
# spf_sieve();
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
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

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

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()));

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

## taking string array input
def str_array():
    return input().strip().split();

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

## for checking any conditions
def check(beauty, s, n, count):
	pass

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
alphs = "abcdefghijklmnopqrstuvwxyz"

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################

from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect
# import numpy as np

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)

# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py

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):
    """Prints the values to a stream, or to sys.stdout by default."""
    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")

# endregion

if __name__ == "__main__":
    #read()
    # sys.stdin = open("input.txt", "r")
    # sys.stdout = open("output.txt", "w")
    for i in range(1):
    	solve()
    #dmain()

# Comment Read()
	# fin_time = datetime.now()
# 	print("Execution time (for loop): ", (fin_time-init_time))

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

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

def A546():
    k,n,w = map(int, raw_input().split())
    count = (1+w)*w*k*0.5
    if count > n :
        print int(count -n)
    else:
        print 0

def B546():
    n = int(raw_input())
    a = map(int, raw_input().split())

    d = {} # dict
    count = 0
    for i in range(n):
        while str(a[i]) in d :
            a[i]+=1
            count+=1
        d[str(a[i])] = 1
    #print d
    print count

def C546():
     n = int(raw_input())
     l=lambda:map(int,raw_input().split())
     a = l()[1:]
     b = l()[1:]
     c = 0
     R = set()
     while a and b:
         c +=1
         A = a.pop(0)
         B = b.pop(0)
         if A > B:
             a+=[B,A]
         else:
             b+=[A,B]
         r =(tuple(a),tuple(b))
         if r in R :
             print -1
             exit(0)
         R.add(r)
     print c, 1 if a else 2

if __name__=='__main__':
    #A546()
    #B546()
    C546()

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)

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(raw_input())
k1 = map(int, raw_input().split()[1:])
k2 = map(int, raw_input().split()[1:])
for turn in xrange(1, 107):
    a, b = k1.pop(0), k2.pop(0)
    if   a > b:
        k1.append(b)
        k1.append(a)
    elif a < b:
        k2.append(a)
        k2.append(b)
    if   not k2:
        print turn, 1
        break
    elif not k1:
        print turn, 2
        break
else:
    print -1

n=int(input())

x1=map(int,raw_input().split())
x2=map(int,raw_input().split())
k1=x1[0]
k2=x2[0]
p1=x1[1:]
p2=x2[1:]
count=0
win=0

i=0
while( i<=1000000 and len(p1)!=0 and len(p2)!=0):
	if(p1[0] < p2[0]):
		p2.append(p1[0])
		p1.remove(p1[0])
		p2.append(p2[0])
		p2.remove(p2[0])
	else:
		p1.append(p2[0])
		p2.remove(p2[0])
		p1.append(p1[0])
		p1.remove(p1[0])
	i+=1

if(len(p1)==0):
	print i,2
elif(len(p2)==0):
	print i,1
else:
	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)

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

import copy
n = int(raw_input())

A = map(int, raw_input().split())
A.pop(0)

B = map(int, raw_input().split())
B.pop(0)

buf = list()
count = 0
while len(A) > 0 and len(B) > 0:
	buf.append(copy.deepcopy([A, B]))

	if A[0] < B[0]:
		tmp = B[0]
		B.pop(0)
		B.append(A[0])
		B.append(tmp)
		A.pop(0)

	else:
		tmp = A[0]
		A.pop(0)
		A.append(B[0])
		A.append(tmp)
		B.pop(0)

	count += 1
	if [A, B] in buf:
		print -1
		exit()

win = 1 if len(A) > 0 else 2
print count, win

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)

# WeirdBugsButOkay

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)

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)

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)

'''
---------------vishva-mitra----------------

'''
import Queue

N = int(raw_input())
tmp = map(int, raw_input().strip().split(' '))
q1 = Queue.Queue()
for x in tmp[1:] :
    q1.put(x)
tmp = map(int, raw_input().strip().split(' '))
q2 = Queue.Queue()
for x in tmp[1:] :
    q2.put(x)

dic = {(tuple(q1.queue), tuple(q2.queue)):True}
res = 0
while 1 :
    tmp1 = q1.get()
    tmp2 = q2.get()
    if tmp1 > tmp2 :
        q1.put(tmp2)
        q1.put(tmp1)
    else :
        q2.put(tmp1)
        q2.put(tmp2)
    tmp = (tuple(q1.queue), tuple(q2.queue))
    if tmp in dic :
        print -1
        exit(0)
    dic[tmp] = True
    res += 1
    if q1.qsize() == 0:
        print res,2
        exit(0)
    if q2.qsize() == 0 :
        print res,1
        exit(0)

n = int(input())
a = list(map(int, input().split()[1:]))
b = list(map(int, input().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)

def main():
    #gathering data
    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
    # history.append(p1cards)
    # history.append(p2cards)
    # if (p1cards[0] > p2cards[0]):
    #     p1cards, p2cards = switchero(p1cards,p2cards)
    # elif (p2cards[0] > p1cards[0]):
    #     p2cards, p1cards = switchero(p2cards,p1cards)

    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

if __name__ == "__main__": main()

#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)
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)
        else:
            if len(b)==0:
                print(cnt,1)
            else :
                print(cnt,2)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    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())

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)

from sys import stdin,stdout,setrecursionlimit,maxint,exit
#setrecursionlimit(2*10**5)
def listInput():
 return map(long,stdin.readline().split())
def printBS(li):
 if not li: return
 for i in xrange(len(li)-1):
  stdout.write("%d "%li[i])
 stdout.write("%d\n"%li[-1])
def sin():
 return stdin.readline().rstrip()
from collections import deque
n=input()
s1=deque(listInput()[1:])
s2=deque(listInput()[1:])
tied=False
states=set([])
turns=0
while s1 and s2:
 if (tuple(s1),tuple(s2)) in states:
  tied=True
  break
 else: states.add((tuple(s1),tuple(s2)))
 a=s1.popleft()
 b=s2.popleft()
 if a>b:
  s1.append(b)
  s1.append(a)
 else:
  s2.append(a)
  s2.append(b)
 turns+=1
if tied:
 print -1
else:
 if s1:
  print turns,1
 else: print turns,2

#*+++++++++++++++++++++
# * Written By --------
# * Boddapati Mahesh  **
# * IIIT Hyderabad *****
# */

import sys

li=[]

l=[]

m=[]

p=()

q=()

dic={}

n=input()

li=map(int,raw_input().split())

li.reverse()

for i in range(0,len(li)-1):
    l.append(li[i])

li=map(int,raw_input().split())

li.reverse()

for i in range(0,len(li)-1):
    m.append(li[i])

count=0

while(1):
    if(len(l)==0):
        sys.stdout.write(str(count))
        sys.stdout.write(" ")
        sys.stdout.write('2')
        break
    elif(len(m)==0):
        sys.stdout.write(str(count))
        sys.stdout.write(" ")
        sys.stdout.write('1')
        break
    else:
        p=tuple(l)
        q=tuple(m)
        if(p in dic and q in dic):
            sys.stdout.write('-1')
            break
        else:
            if(p in dic):
                dic[q]=1
            elif(q in dic):
                dic[p]=1
            else:
                dic[p]=1
                dic[q]=1
            a=l.pop()
            b=m.pop()
            if(a<b):
                m.insert(0,a)
                m.insert(0,b)
            elif(b<a):
                l.insert(0,b)
                l.insert(0,a)
            count+=1
print

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import time
import sys
import io
import re
import math
import itertools
from collections import deque
import copy
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
#start = time.clock()
n=int(raw_input())
#n,k=map(int,raw_input().split())

def lst():
    x=deque()
    l=map(int,raw_input().split())
    for i in range(1,l[0]+1):
        x.appendleft(l[i])
    return x

l=lst()
r=lst()
tmp_l=copy.copy(l)
tmp_r=copy.copy(r)
cnt=1
t=106
while t:
    p=l.pop()
    q=r.pop()

    if p>q:
        l.appendleft(q)
        l.appendleft(p)
    else:
        r.appendleft(p)
        r.appendleft(q)
    if len(l)==0:
        print cnt,2
        exit()
    elif len(r)==0:
        print cnt,1
        exit()
    elif tmp_r==r and tmp_l==l:
        print -1
        exit()
    cnt+=1
    t-=1
print -1

n = int(raw_input())

p1 = map(int, raw_input().split(" "))
p2 = map(int, raw_input().split(" "))

p1 = p1[1:]
p2 = p2[1:]

turns = 0
i = 0
j = 0

found = set([])

new_p1 = []
new_p2 = []
found.add((tuple(p1), tuple(p2)))

count = 0
infinite = False

while (len(p1) + len(new_p1) - i > 0 and len(p2) + len(new_p2) - j > 0):
	if not (i < len(p1) and j < len(p2)):
		p1 = p1[i:] + new_p1
		p2 = p2[j:] + new_p2
		new_p1 = []
		new_p2 = []
		i = 0
		j = 0

		tp1, tp2 = tuple(p1), tuple(p2)
		if (tp1, tp2) in found:
			infinite = True
			break
		else:
			found.add((tp1, tp2))

	nump1 = p1[i]
	nump2 = p2[j]
	i += 1;
	j += 1;

	if nump1 > nump2:
		new_p1.append(nump2)
		new_p1.append(nump1)
	else:
		new_p2.append(nump1)
		new_p2.append(nump2)
	count += 1

if infinite:
	print -1
elif len(p1) + len(new_p1) - i == 0:
	print count, 2
else:
	print count, 1

from collections import deque
from math import factorial

n = int(input())
a1 = deque(map(int,input().split()))
a1.popleft()
a2 = deque(map(int,input().split()))
a2.popleft()

cnt = 0
f = factorial(n)
while len(a1) != 0 and len(a2) != 0 and cnt <= f:

    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
#print(cnt)
if cnt > f :
    print('-1')

else:
    print(cnt , end = ' ')
    if len(a1) == 0 :
        print(2)
    else:
        print(1)

def pick_card(k, stack):
	k -= 1
	devide = 10**(2*k)
	card = stack / devide
	stack = stack % devide
	return k, card, stack

def puts_card(k, stack, card_w, card_l):
	k += 2
	return k, stack*10000 + card_l*100 + card_w

n = int(raw_input())
inputs = map(int,raw_input().split(" "))
k1 = int(inputs[0])
stack1 = sum((inputs[i]) * (10 ** (2*(k1-i))) for i in range(1,k1+1))
inputs = map(int,raw_input().split(" "))
k2 = int(inputs[0])
stack2 = sum((inputs[i]) * (10 ** (2*(k2-i))) for i in range(1,k2+1))

played = set([(stack1,stack2)])
fight = 0
while 1:
	fight += 1
	k1, card1, stack1 = pick_card(k1, stack1)
	k2, card2, stack2 = pick_card(k2, stack2)
	if card1 > card2:
		k1, stack1 = puts_card(k1, stack1, card1, card2)
	else:
		k2, stack2 = puts_card(k2, stack2, card2, card1)

	if k1 == 0:
		print fight, 2
		break
	elif k2 == 0:
		print fight, 1
		break
	elif (stack1, stack2) in played:
		print -1
		break
	else:
		played.add((stack1,stack2))

x=int(input())
A=list(map(int,input().split()))
A=A[1:]
#print(A)
D=A
#print(D)
B=list(map(int,input().split()))
B=B[1:]
E=B
C=[]
#print(A)
#print(B)
count=0
num=1000
while(num>0):
	if count==999:
		state=10000
		break
	#print(D)
	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
		#print(A,B)
		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
			#print(A,B)
			num=num-1
	#if A==D:
	#	if B==E:
	#		state=1000
	#		break
	#if A==E:
	#	if B==D:
	#		state=1000
	#		break
if state==10:
	print (count,2)
if state==100:
	print (count,1)
#CODE BASED ON THE TEST CASES
#MAHESH JASTI
#IIIT HYDERABAD
if state==10000:
	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=input()
s=set()
a=[map(lambda x: int(x)-1,raw_input().split())[1:] for _ in range(2)]
G=lambda: str(a[0])+' '+str(a[1])
s.add(G())
cnt=0
while 1:
    cnt+=1
    k=1 if a[0][0]<a[1][0] else 0
    a[k]+=[a[k^1][0], a[k][0]]
    a[k].pop(0)
    a[k^1].pop(0)
    state=G()
    if state in s:
        print -1
        break
    if not a[0] or not a[1]:
        print cnt, k+1
        break
    s.add(state)

n = int(raw_input())

k1 = [int(x) for x in raw_input().split()]
k2 = [int(x) for x in raw_input().split()]

visited = set()

turns = 0
impossible = False
won = None
def recurse(a, b):
    global turns
    global won
    global impossible
    tup_a, tup_b = tuple(a), tuple(b)
    if (tup_a, tup_b) in visited:
        impossible = True
    else:
        visited.add((tup_a, tup_b))
        top_a = a.pop()
        top_b = b.pop()
        turns += 1

        if top_a > top_b:
            a = [top_a, top_b] + a
            if len(b) == 0:
                won = 1
            else:
                recurse(a, b)
        else:
            b = [top_b, top_a] + b
            if len(a) == 0:
                won = 2
            else:
                recurse(a, b)
recurse(k1[1:][::-1], k2[1:][::-1])
if impossible:
    print -1
else:
    print turns, won

n=int(raw_input())
l=map(int,raw_input().split())
m=map(int,raw_input().split())
l=l[1:]
m=m[1:]
a=0
p=[[c for c in l]]
q=[[c for c in m]]
#print p
while len(l)>0 and len(m)>0:
    if l[0]>m[0]:
        l=l[1:]+[m[0],l[0]]
        m=m[1:]
        a+=1
        #print l+['l']
        #print m+['m']
        if l in p and m in q:
            break
        else:
            p.append(l)
            q.append(m)
    else:
        m=m[1:]+[l[0],m[0]]
        l=l[1:]
        a+=1
        #print l+['l']
        #print m+['m']
        if l in p and m in q:
            break
        else:
            p.append(l)
            q.append(m)
if len(l)==0:
    print str(a)+' '+str(2)
elif len(m)==0:
    print str(a)+' '+str(1)
else:
    print -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)

from math import *
from collections import deque
from copy import deepcopy
import sys
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
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))  #for fast output, always take string
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

#copied functions end

#start coding

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

    # if(check(a,b,initiala,initialb,ans)):
    #     print(-1)
    #     exit(0)

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()))
#for deque append(),pop(),appendleft(),popleft(),count()
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):
   # print(c,d)
    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)

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
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
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)
    # print(s1, s2)
    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)))

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

n = int(raw_input())

s1 = map(int, raw_input().split())[1:]
s2 = map(int, raw_input().split())[1:]
s1.reverse()
s2.reverse()

def make_state():
    return ','.join(map(str, s1)) + ';' + ','.join(map(str, s2))

states = list()
states.append(make_state())

run = True
hits = 0
while s1 and s2:
    hits += 1
    k1 = s1.pop()
    k2 = s2.pop()

    if k1 > k2:
        s1.insert(0, k2)
        s1.insert(0, k1)
    else:
        s2.insert(0, k1)
        s2.insert(0, k2)

    state = make_state()
    if state in states:
        print -1
        exit()

    states.append(state)

winner = 1 if s1 else 2
print hits, winner

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)

l=lambda:map(int,raw_input().split())[1:]
input()
a=l()
b=l()
r=0
while a and b:
    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]
    r+=1
print r,1 if a else 2

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, k = map(int, input().split(" "))
# l = list(map(int, input().split(" ")))
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
    else:

        if 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())
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())
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=" ")

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

def check(A, B):
    count = 0

    d = {}
    s1 = ''.join(map(str, A))
    s2 = ''.join(map(str, B))
    d[s1] = True
    d[s2] = True

    while len(A) and len(B):
        count += 1
        a, b = A.pop(0), B.pop(0)

        if a > b:
            A.append(b)
            A.append(a)
        else:
            B.append(a)
            B.append(b)

        s1 = ''.join(map(str, A))
        s2 = ''.join(map(str, B))

        if s1 in d and s2 in d:
            print -1
            return -1

        if not s1 in d:
            d[s1] = True

        if not s2 in d:
            d[s2] = True

    if len(A) == 0:
        print count, 2
    else:
        print count, 1

n = int(raw_input())

A = map(int, raw_input().split())
k1 = A.pop(0)
B = map(int, raw_input().split())
k2 = B.pop(0)

check(A, B)

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>1e7: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>1e7:print(-1)
else :
        if len(lst1)==0:
                print(cnt , 2)
        else :
                print(cnt , 1)

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

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

__author__ = '11x256'
from Queue import deque
n = int(raw_input())

a = deque(map(int,raw_input().split()))
b = deque(map(int,raw_input().split()))

a.popleft()
b.popleft()

wars =0
for i in range(0,1000):
    if len(a) == 0:
        print str(wars)+' '+'2'
        exit()
    elif len(b) == 0 :
        print str(wars) + ' 1'
        exit()
    wars+=1

    ta = a.popleft()
    tb = b.popleft()
    if ta > tb:
        a.append(tb)
        a.append(ta)
    else:
        b.append(ta)
        b.append(tb)
print -1

'''input
4
2 1 3
2 4 2
'''

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)

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)

'''input
3
1 2
2 1 3
'''
# connected components
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

# main starts
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()
a=[int(i) for i in raw_input().split()]
b=[int(i) for i in raw_input().split()]
k1=a[0]
a=a[1:]
k2=b[0]
b=b[1:]
d={}
f=0
turns=0
while(k1>0 and k2>0):
    ta=a[0]
    tb=b[0]
    turns+=1
    if ta>tb:
        a.pop(0)
        b.pop(0)
        a=a+[tb,ta]
        k1+=1
        k2-=1
        tup=tuple(a+b+[k1])
        if tup in d:
            f=1
            break
        else:
            d[tup]=True

    else:
        a.pop(0)
        b.pop(0)
        b=b+[ta,tb]
        k2+=1
        k1-=1
        tup=tuple(a+b+[k1])
        if tup in d:
            f=1
            break
        else:
            d[tup]=True
if f==1:
    print -1
else:
    if k1==0:
        print turns,2
    else:
        print turns,1

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

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

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)

#ahora hago el juego

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

r = lambda :map(int,raw_input().split())
n = input()
a = r()[1:]
b = r()[1:]
path = set(str([a,b]))
c = 0
while 1:
	c+=1
	if a[0]>b[0]:
		a.extend([b[0],a[0]])
		a = a[1:]
		b = b[1:]
	else:
		b.extend([a[0],b[0]])
		a = a[1:]
		b = b[1:]
	d = str([a,b])
	if d in path:
		print -1
		exit(0)
	else:
		path.add(d)
		if len(a)==0:
			print c,2
			exit(0)
		if len(b)==0:
			print c,1
			exit(0)

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)

#!/usr/bin/python
# -*- encoding: utf-8 -*-
# pylint: disable=invalid-name,missing-docstring,bad-builtin
from collections import deque

def main():
    raw_input()
    pl1 = deque(reversed(map(int, raw_input().split())))
    pl1.pop()
    pl2 = deque(reversed(map(int, raw_input().split())))
    pl2.pop()
    visitedStates, steps = set(), 0
    while True:
        if not (pl1 and pl2):
            print steps, (1 if pl1 else 2)
            return
        if tuple(pl1) + tuple(pl2) in visitedStates:
            print -1
            return
        visitedStates.add(tuple(pl1) + tuple(pl2))
        x, y = pl1.pop(), pl2.pop()
        if x > y:
            pl1.appendleft(y)
            pl1.appendleft(x)
        else:
            pl2.appendleft(x)
            pl2.appendleft(y)
        steps += 1

main()

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
	# print(a, temp_a)

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

l=lambda:map(int,raw_input().split())[1:]
input()
a=l()
b=l()
r=0
while a and b:
    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]
    r+=1
print r,1 if a else 2

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:
    # print(L, R)
    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))

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
    #print(l1,l2)
    if(cou==100000):
        break
if(len(l1)==0):
    print(cou,2)
elif(len(l2)==0):
    print(cou,1)
else:
    print(-1)

"""http://codeforces.com/problemset/problem/546/C"""

def hash(a, b):
    return '{}_{}'.format(''.join(map(str, a)), ''.join(map(str, b)))

def solve(a, b):
    state = set()
    count = 0
    while len(a) > 0 and len(b) > 0:
        if hash(a, b) in state:
            return -1
        state.add(hash(a, b))
        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

if __name__ == '__main__':
    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())
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)

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

## necessary imports
import sys
input = sys.stdin.readline
from math import ceil, floor;

# swap_array function
def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp

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

## nCr function efficient using Binomial Cofficient
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)

## upper bound function code -- such that e in a[:i] e < x;
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

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    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
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

## MODULAR EXPONENTIATION FUNCTION
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

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
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;

# the union function which makes union(x,y)
# of two nodes x and y
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

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
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

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 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;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
    ret = {};
    while x != 1:
        ret[spf[x]] = ret.get(spf[x], 0) + 1;
        x = x//spf[x]
    return ret
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()))
## taking string array input
def str_array():
    return input().strip().split();

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################

n = int(input()); a = int_array(); b = int_array();
k1 = a[0]; a = a[1:]; k2 = b[0]; b = b[1:];
ia = a.copy(); ib = b.copy();
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 (a == ia and b == ib) or count == 100000:
        break;
if f:
    print(*(count, won));
else:
    print(-1);

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

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)

def check(A, B):
    count = 0

    d = {}
    s1 = ''.join(map(str, A))
    s2 = ''.join(map(str, B))
    d[s1] = True
    d[s2] = True

    while len(A) and len(B):
        count += 1
        a, b = A.pop(0), B.pop(0)

        if a > b:
            A.append(b)
            A.append(a)
        else:
            B.append(a)
            B.append(b)

        s1 = ''.join(map(str, A))
        s2 = ''.join(map(str, B))

        if s1 in d and s2 in d:
            print -1
            return -1

        if not s1 in d:
            d[s1] = True

        if not s2 in d:
            d[s2] = True

    if len(A) == 0:
        print count, 2
    else:
        print count, 1

n = int(raw_input())

A = map(int, raw_input().split())
k1 = A.pop(0)
B = map(int, raw_input().split())
k2 = B.pop(0)

check(A, B)

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)

def to_s(array):
    return ",".join(map(str, array))

def to_hash(k1, k2):
    return to_s(k1) + ":" + to_s(k2)

def add_states(states, k1, k2):
    states[to_hash(k1, k2)] = True
    states[to_hash(k2, k1)] = True

def nextState(winner, loser):
    c1 = winner.pop(0)
    c2 = loser.pop(0)
    winner.extend([c2, c1])

n = int(raw_input())
k1 = map(lambda x: int(x), raw_input().split(" "))[1:]
k2 = map(lambda x: int(x), raw_input().split(" "))[1:]

count = 0
states = {}
add_states(states, k1, k2)

while len(k1) != 0 and len(k2) != 0:
    count += 1

    if k1[0] > k2[0]:
        nextState(k1, k2)
    else:
        nextState(k2, k1)

    if states.has_key(to_hash(k1, k2)):
        count = -1
        break

    add_states(states, k1, k2)

if count == -1:
    print count
else:
    print u"%d %d" % (count, 1 if len(k1) != 0 else 2)

"""
    Author - Satwik Tiwari .
    27th Oct , 2020  - Tuesday
"""

#===============================================================================================
#importing some useful libraries.

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 itertools import *
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

#==============================================================================================
#fast I/O region
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):
    """Prints the values to a stream, or to sys.stdout by default."""
    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)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
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
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
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 graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
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     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        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
#===============================================================================================
# code here ;))

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)
# testcase(int(inp()))

from collections import deque
import math

n = int(raw_input())
l1 = raw_input().split(" ")
l1 = [int(l1[i]) for i in range(1,int(l1[0])+1)]
l2 = raw_input().split(" ")
l2 = [int(l2[i]) for i in range(1,int(l2[0])+1)]
l1 = deque(l1)
l2 = deque(l2)

c1 = l1[0]
c2 = l2[0]

m = math.sqrt((n+1) * (math.factorial(n)))

c = 0
f = 0
s = 0

while len(l1) != 0 and len(l2) != 0:
    a = l1.popleft()
    b = l2.popleft()

    if c >= m:
        print -1
        f = 1
        break

    if a < b:
        l2.append(a)
        l2.append(b)
    else:
        l1.append(b)
        l1.append(a)

    s = 1
    c = c+1

if f == 0:
    if len(l1) == 0:
        print c, 2
    else:
        print c, 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)
   # print(len(dec1))
    #print(len(dec2))
if(isAnswer==False):
    print(-1)

from copy import deepcopy as dcp
n = int(raw_input())
stack1 = map(int,raw_input().split(" "))
init1 = dcp(stack1)
stack2 = map(int,raw_input().split(" "))
init2 = dcp(stack2)
fight = 0
while 1:
	fight += 1
	card1 = stack1.pop(1)
	stack1[0] -= 1
	card2 = stack2.pop(1)
	stack2[0] -= 1
	if card1 > card2:
		stack1 += [card2, card1]
		stack1[0] += 2
	elif card2 > card1:
		stack2 += [card1, card2]
		stack2[0] += 2
	if stack1[0] == 0:
		print fight, 2
		break
	elif stack2[0] == 0:
		print fight, 1
		break
	if stack1 == init1 and stack2 == init2 or fight == 100000:
		print -1
		break

n=input()
k1=raw_input().split(' ')
k2=raw_input().split(' ')
#import time
#start_time = time.clock()
k1f=[None]*(len(k1)-1)
k2f=[None]*(len(k2)-1)
for i in range(len(k1)-1):
    k1[i]=int(k1[i])
    k1f[i]=int(k1[i+1])
for i in range(len(k2)-1):
    k2[i]=int(k2[i])
    k2f[i]=int(k2[i+1])
k1[len(k1)-1]=int(k1[len(k1)-1])
k2[len(k2)-1]=int(k2[len(k2)-1])
fight=0
k1.remove(k1[0])
k2.remove(k2[0])
while len(k1)!=0 and len(k2)!=0:
    if k1[0]>k2[0]:
        x=k1[0]
        y=k2[0]
        k1.remove(k1[0])
        k2.remove(k2[0])
        k1=k1+[y]+[x]
        fight=fight+1
    else:
        x=k2[0]
        y=k1[0]
        k1.remove(k1[0])
        k2.remove(k2[0])
        k2=k2+[y]+[x]
        fight=fight+1
    #print k1,k2
    if k1==k1f and k2==k2f or fight>106:
        print -1
        break
if len(k1)==0:
        print fight,2
elif len(k2)==0:
        print fight,1
#print("--- %s seconds ---" % (time.clock() - start_time))

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)

n = int(raw_input())
ar1 = map(int,raw_input().split())
ar2 = map(int,raw_input().split())
n1 = ar1[0]
n2 = ar2[0]
ar1 = ar1[1:]
ar2 = ar2[1:]
cnt = 0
while ar1!=[] and ar2 !=[] and cnt<108:
    if ar1[0]>ar2[0]:
        ar1.append(ar2[0])
        ar1.append(ar1[0])
        ar2 = ar2[1:]
        ar1 = ar1[1:]
    else:
        ar2.append(ar1[0])
        ar2.append(ar2[0])
        ar1 = ar1[1:]
        ar2 = ar2[1:]
    cnt += 1

if ar1==[]:
    print cnt,2
elif ar2==[]:
    print cnt,1
else:
    print -1

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)

visited = []
winner = -1
if len(p1) <= len(p2):
    visited.append(list(p1))
else:
    visited.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 visited or p2 in visited:
        print(winner)
        break

    if len(p1) <= len(p2):
        visited.append(list(p1))
    else:
        visited.append(list(p2))
    fights += 1

n=int(raw_input())
s1=raw_input().split()
s2=raw_input().split()
a=[]
p1=[]
p2=[]
for i in range(1,len(s1)):
    p1.append(int(s1[i]))
for i in range(1,len(s2)):
    p2.append(int(s2[i]))
a.append((tuple(p1),tuple(p2)))
c=0
f=0
while len(p1)!=0 and len(p2)!=0:
    if p1[0]>p2[0]:
        p1.append(p2[0])
        p1.append(p1[0])
    else:
        p2.append(p1[0])
        p2.append(p2[0])
    del(p1[0])
    del(p2[0])
    c+=1
    for j in a:
        if j[0]==tuple(p1):
            f=1
            break
    if f==1:
        break
    a.append((tuple(p1),tuple(p2)))
if f==0:
    print c
else:
    print -1

n=input()
a=raw_input()
a=a.split()
a=map(int,a)
b=raw_input()
b=b.split()
b=map(int,b)
a.pop(0)
b.pop(0)
ans=0

a_config=list()
b_config=list()
a_config.append(list(a))
while(len(a)!=0 and len(b)!=0):
    #print a,b,a_config
    if a[0]>b[0]:
        a.append(b[0])
        a.append(a[0])
        a.pop(0)
        b.pop(0)
        if a not in a_config:
            a_config.append(list(a))
        else:
            #print "hi"
            print "-1"
            exit(0)
        ans+=1
    else:
        b.append(a[0])
        b.append(b[0])
        a.pop(0)
        b.pop(0)
        ans+=1
        #print a,a_config
        if a not in a_config:
            a_config.append(list(a))
        else:
            print "-1"
            exit(0)
print ans

## necessary imports
import sys
input = sys.stdin.readline
from math import ceil, floor;

# swap_array function
def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp

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

## nCr function efficient using Binomial Cofficient
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)

## upper bound function code -- such that e in a[:i] e < x;
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

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    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
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

## MODULAR EXPONENTIATION FUNCTION
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

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
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;

# the union function which makes union(x,y)
# of two nodes x and y
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

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
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

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 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;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
    ret = {};
    while x != 1:
        ret[spf[x]] = ret.get(spf[x], 0) + 1;
        x = x//spf[x]
    return ret
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()))
## taking string array input
def str_array():
    return input().strip().split();

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################

n = int(input()); a = int_array(); b = int_array();
k1 = a[0]; a = a[1:]; k2 = b[0]; b = b[1:];
ia = a.copy(); ib = b.copy();
count = 0; f = 0; won = 2;
while(1):
    if not a or not b:
        f = 1; break;
    count += 1;
    if won == 2:
        won = 1;
    else:
        won = 2;
    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 == ia and b == ib:
        break;
if f:
    print(*(count, won));
else:
    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

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)
    else:
        B.append(c)
        B.append(d)
    br+=1
if br>=300000:
    print(-1)
else:
    print(br)

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<100:
    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)

cards = int(input())
start_first = input().split()[1:]
start_second = input().split()[1:]

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 == start_first or s == start_second:
        print (-1)
        break
else:
    print (rounds, (1,2)[f == []])

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=0
print(listt_1,listt_2)
while True:
    print(listt_1[0],listt_2[0])
    if(listt_1[0]>listt_2[0]):
        print(1)
        j=listt_2.pop(0)
        i=listt_1.pop(0)
        listt_1.append(j)
        listt_1.append(i)
    else:
        print(2)
        j = listt_1.pop(0)
        i = listt_2.pop(0)
        listt_2.append(j)
        listt_2.append(i)
    no+=1
    print(no,listt_1,listt_2)
    if(len(listt_1)==0):
        print(no,"2")
        break
    if (len(listt_2) == 0):
        print(no, "1")
        break
    if(listt_1==list_1 and listt_2==list_2):
        print("-1")
        break

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>100:
        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))

n = int(raw_input())

A = map(int, raw_input().split())
A.pop(0)

B = map(int, raw_input().split())
B.pop(0)

A_buf = []
count = 0
while len(A) > 0 and len(B) > 0:
	A_buf.append(list(A))

	if A[0] < B[0]:
		tmp = B[0]
		B.pop(0)
		B.append(A[0])
		B.append(tmp)
		A.pop(0)

	else:
		tmp = A[0]
		A.pop(0)
		A.append(B[0])
		A.append(tmp)
		B.pop(0)

	count += 1
	if A in A_buf:
		print -1
		exit()

win = 1 if len(A) > 0 else 2
print count, win

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+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+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]

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>100:
    print(-1)
else:
    if s1:
        print(t, 1)
    else:
        print(t, 2)

n=int(raw_input())
l=map(int,raw_input().split())
m=map(int,raw_input().split())
l=l[1:]
m=m[1:]
a=0
p=[[c for c in l]]
#print l
while len(l)>0 and len(m)>0:
    if l[0]>m[0]:
        l=l[1:]+[m[0],l[0]]
        m=m[1:]
        a+=1
        #print l
        if l in p:
            break
        else:
            p.append(l)
    else:
        m=m[1:]+[l[0],m[0]]
        l=l[1:]
        a+=1
        #print l
        if l in p:
            break
        else:
            p.append(l)
if len(l)==0:
    print str(a)+' '+str(2)
elif len(m)==0:
    print str(a)+' '+str(1)
else:
    print -1

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
# visited = set()
loopcount = 100
while k1nums and k2nums and loopcount:
    loopcount -= 1
    top1, top2 = k1nums.popleft(), k2nums.popleft()
    # l = len(k1nums)
    # if (top1, top2, l, n - l) in visited:
    #     print(-1)
    #     flag = 0
    #     break
    # else:
    #     visited.add((top1, top2, l, n - l))

    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)

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)

fight_map = [[0 for _ in range(n+1)] for __ in range(n+1)]
draw = False
counter = 0

while True:
    try:
        card1 = player1.popleft()
        card2 = player2.popleft()

        # print(f"{card1} {card2}")
    except IndexError:
        # one of the stack is empty
        break

    if fight_map[card1][card2] == 1:
        draw = True
        break

    if card1 > card2:
        # player 1 wins

        # add player2's card to player1's stack
        player1.append(card2)
        # add player1's card to player1's stack
        player1.append(card1)
    else:
        # player 2 wins

        player2.append(card1)
        player2.append(card2)

    fight_map[card1][card2] = 1
    counter += 1

if draw:
    print(-1)
else:
    try:
        player1.pop()
    except IndexError:
        print(f"{counter} 2")
    try:
        player2.pop()
    except IndexError:
        print(f"{counter} 1")

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)

n = int(raw_input())

A = map(int, raw_input().split())
A.pop(0)

B = map(int, raw_input().split())
B.pop(0)

buf = list()
count = 0
while len(A) > 0 and len(B) > 0:
	buf.append([A, B])

	if A[0] < B[0]:
		tmp = B[0]
		B.pop(0)
		B.append(A[0])
		B.append(tmp)
		A.pop(0)

	else:
		tmp = A[0]
		A.pop(0)
		A.append(B[0])
		A.append(tmp)
		B.pop(0)

	count += 1
	if [A, B] in buf:
		print -1
		exit()

win = 1 if len(A) > 0 else 2
print count, win

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

    aconf = {tuple(a)}
    i = 1
    while True:
        x, y = a.pop(), b.pop()
        if x > y:
            a.appendleft(y)
            a.appendleft(x)
        else:
            b.appendleft(x)
            b.appendleft(y)

        atuple = tuple(a)
        if atuple in aconf:
            print(-1)
            return
        else:
            aconf.add(atuple)

        if not a:
            print(i, 2)
            return

        if not b:
            print(i, 1)
            return

        i += 1

if __name__ == '__main__':
    main()

import math
#n,m=map(int,input().split())
from collections import Counter
#for i in range(n):
import math
#for _ in range(int(input())):
#n = int(input())
#for _ in range(int(input())):
#n = int(input())
import bisect
'''for _ in range(int(input())):

    n=int(input())

    n,k=map(int, input().split())

    arr = list(map(int, input().split()))'''
#n, m, k = [int(x) for x in input().split()]
#n,m=map(int,input().split())
n=int(input())
arr = list(map(int, input().split()))
arr=arr[1:]
a=arr
ls = list(map(int, input().split()))
ls=ls[1:]
b=ls
cnt=0
while arr and ls:

    cnt+=1
    if arr[0]>ls[0]:
        arr=arr[1:]+[ls[0]]+[arr[0]]
        ls=ls[1:]

    else:
        ls=ls[1:]+[arr[0]]+[ls[0]]
        arr=arr[1:]
    if arr==a or ls==b:
        print(-1)
        exit()
ans= 2 if arr==[] else 1

print(cnt, ans)

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):
    print(a,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)

from collections import deque
n = int(input())
list1 = list(map(int, input().split()))
list2 = list(map(int, input().split()))
k1 = list1[0]
k2 = 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()

never_end = False

while len(q1) and len(q2):
    fights += 1
    a = q1.popleft()
    b = q2.popleft()
    if (a, b) in seen:
        never_end = True
        break
    else:
        seen.add((a, b))
    if a > b:
        q1.append(b)
        q1.append(a)
    else:
        q2.append(a)
        q2.append(b)

if never_end:
    print(-1)
else:
    if len(q1):
        print(fights, 1)
    else:
        print(fights, 2)

n = input()
l = raw_input().split()
k1 = int(l[0])
c1 = []
for i in range(1, len(l)):
    c1.append(int(l[i]))
l = raw_input().split()
k2 = int(l[0])
c2 = []
for i in range(1, len(l)):
    c2.append(int(l[i]))
turn = 0
flag = -1
for i in range(0, 100):
    if len(c1) == 0:
        flag = 2
        break
    elif len(c2) == 0:
        flag = 1
        break
    if c1[0] > c2[0]:
        c1.append(c2[0])
        c1.append(c1[0])
        c1 = c1[1:]
        c2 = c2[1:]
    else:
        c2.append(c1[0])
        c2.append(c2[0])
        c2 = c2[1:]
        c1 = c1[1:]
    turn += 1

if flag != -1:
    print turn,
    print flag
else:
    print -1

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

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]
count = 1

while not all_equal(temp_a, a) and len(temp_a) and len(temp_b):
	a.append(temp_a)
	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
	# print(a, temp_a)

if not len(temp_a):
	print(count, 2)
elif not len(temp_b):
	print(count, 1)

else:
	print(-1)

import sys

n = int(raw_input())
xcards = map(int, raw_input().split())
x = xcards[0]
xcards = xcards[1:]
y = n - x
ycards = map(int, raw_input().split())[1:]

fights = 0
states = set()
while xcards and ycards:
    fights += 1
    xval = xcards.pop(0)
    yval = ycards.pop(0)
    if xval > yval:
        xcards.append(yval)
        xcards.append(xval)
    else:
        ycards.append(xval)
        ycards.append(yval)

    if tuple(xcards + ycards) in states:
        print -1
        sys.exit(0)
    states.add(tuple(xcards + ycards))
print fights, 1 if xcards else 2

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:
        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 fights>10000:
    print(-1)
elif len(player1)==0:
    print(fights,2)
else:
    print(fights,1)

import sys
n=input()

l1=raw_input().split()
a=l1[0]
l1=l1[1:]
l2=raw_input().split()
b=l2[0]
l2=l2[1:]

st=""
for e in l1:
    st=st+str(e)

st=st+"a"
for e in l2:
    st=st+str(e)

dic={st:1}

ans=0
ct=1

while ct>-1:

    val1=l1[0]
    val2=l2[0]

    if val1<val2:
        l1=l1[1:]
        a=[val1,val2]
        l2=l2[1:]+a
    else:
        l2=l2[1:]
        a=[val2,val1]
        l1=l1[1:]+a

    if not l1:
        print str(ct)+" 2"
        ct=-2

    if not l2:
        print str(ct)+" 1"
        ct=-2

    st=""
    for e in l1:
        st=st+str(e)
    st=st+"a"
    for e in l2:
        st=st+str(e)

    if st not in dic:
        dic[st]=1
    else:
        print "-1"
        ct=-2
    ct+=1

n = int(raw_input())
A = [int(i) for i in raw_input().split()][1:]
B = [int(i) for i in raw_input().split()][1:]

hash_map = {}

c = 0

while len(A) > 0 and len(B) > 0:
    if ((A[0], B[0]) in hash_map):
        print -1
        raise SystemExit
    hash_map.update({(A[0], B[0]): 1})
    if (A[0] > B[0]):
        A = A[1:] + [B[0], A[0]]
        B = B[1:]
    else:
        B = B[1:] + [A[0], B[0]]
        A = A[1:]
    c += 1

print c,
if len(A):
    print 1
else:
    print 2

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 > 100):
		break

if(iteration > 100):
	print(-1)
	sys.exit()
if(len(k2) != 0):
	print(iteration, 2)
if(len(k1) !=0):
	print(iteration, 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 or k2 in memb:
        print(r,-1)
        break

cards = int(input())
start_first = input().split()[1:]
start_second = input().split()[1:]
hist = []
hist.append((start_first,start_second))
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
    hist.append((f,s))
    if (f,s) in hist:
        print (-1)
        break
else:
    print (rounds, (1,2)[f == []])

#f = open('c:\\users\\arthur\\desktop\\redmart\\numbers.txt')
#d = f.readline().split()
#d = map(int, d)
##d = [3, 2, 4, 5, 6 ,7]
#print d[10000]
#e = d[0]
#y = 0
#step=0
#while step != 10000:
#    if e >=len(d):
#        break
#    step+=1
#    y = e
#    e = d[e]
#    #print step, ' ', e
#print e, ' ',y

import collections

def getStr(x,y):
    s=''
    for i in x:
        s+=str(i)
    for i in y:
        s+=str(i)
    return s

def move(x, y):
    if x[0] > y[0]:
        a = x.popleft()
        b = y.popleft()
        x.append(b)
        x.append(a)
    else:
        a = y.popleft()
        b = x.popleft()
        y.append(b)
        y.append(a)
    return (x,y)

n = int(raw_input())
tmpA = map(int, raw_input().split())
tmpB = map(int, raw_input().split())

#deque A
lA = []
lB = []

for i in range(tmpA[0]):
    lA.append(tmpA[i+1])
for i in range(tmpB[0]):
    lB.append(tmpB[i+1])

hA = collections.deque(lA)
hB = collections.deque(lB)

h = dict()

cnt = 0

while True:
    #print getStr(hA,hB)
    if len(hA)==0:
        #print 'a is empty'
        print str(cnt)+' '+str(2)
        break
    if len(hB)==0:
        #print 'b is empty'
        print str(cnt)+' '+str(1)
        break
    if getStr(hA,hB) in h:
        #print 'there already', ' ',h
        print -1
        break
    else:
        h[getStr(hA,hB)] = True
        #print 'old ', hA,' ',hB
        hA, hB = move(hA,hB)
        #print 'new ', hA,' ',hB

        cnt+=1

import sys
from time import time
T=time()
N=int(raw_input())
K1=map(int,raw_input().split())
K2=map(int,raw_input().split())
Stack1=K1[1:]
Stack2=K2[1:]
I=1
while time()-T<1.7:
    if Stack1[0]>Stack2[0]:
        if len(Stack1)>1:
            Stack1=Stack1[1:]+[Stack2[0]]+[Stack1[0]]
        else:
            Stack1=[Stack2[0]]+[Stack1[0]]
        Stack2.pop(0)
    else:
        if len(Stack1)>1:
            Stack2=Stack2[1:]+[Stack1[0]]+[Stack2[0]]
        else:
            Stack2=[Stack1[0]]+[Stack2[0]]
        Stack1.pop(0)
    if not len(Stack1):
        print I,2
        sys.exit()
    elif not len(Stack2):
        print I,2
        sys.exit()
    I+=1
print -1

n = raw_input("")
k1 = raw_input("")
k2 = raw_input("")
deste_k1 = k1.split()
deste_k2 = k2.split()
deste_k1.remove(deste_k1[0])
deste_k2.remove(deste_k2[0])
el_sayisi = 0
while len(deste_k1) > 0 and len(deste_k2) > 0 and el_sayisi < 200:
    if int(deste_k1[0]) > int(deste_k2[0]) :
        print deste_k1
        print deste_k2
        deste_k1.append(deste_k2[0])
        deste_k2.remove(deste_k2[0])
        deste_k1.append(deste_k1[0])
        deste_k1.remove(deste_k1[0])
        el_sayisi += 1
    elif int(deste_k2[0]) > int(deste_k1[0]) and el_sayisi < 200 :
        print deste_k1
        print deste_k2
        deste_k2.append(deste_k1[0])
        deste_k1.remove(deste_k1[0])
        deste_k2.append(deste_k2[0])
        deste_k2.remove(deste_k2[0])
        el_sayisi += 1
if len(deste_k2) == 0 :
    print el_sayisi , "1"
elif len(deste_k1) == 0 :
    print el_sayisi , "2"
else :
    print "-1"

# Description of the problem can be found at http://codeforces.com/problemset/problem/546/C

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 l_1c == l_1 or t > 400:
        print(-1)
        quit()

print("%d %d" % (t, 2 if len(l_1c) == 0 else 1))

n = input()
a = map(int, raw_input().split())[1:]
b = map(int, raw_input().split())[1:]
ans = 0
t = 0
while a and b:
    if t > 2**n:
        print -1
        exit(0)
    a0 = a.pop(0)
    b0 = b.pop(0)
    if a0 > b0:
        a.append(b0)
        a.append(a0)
    else:
        b.append(a0)
        b.append(b0)
    t += 1

print ans, 1 if a else 2

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=0,0,0,0,[]
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 in l3:
        c=1
        break
    else:
        l3.append(l1)
if c==0:
    if len(l1)==0:
        print(str(b)+' 2')
    else:
        print(str(b)+' 1')
else:
    print(-1)

n=raw_input()
n=int(n)
aa=raw_input().split(' ')
a=[int(i) for i in aa]
bb=raw_input().split(' ')
b=[int(i) for i in bb]
k1=a[0]
k2=b[0]
del a[0]
del b[0]
a0=[]
b0=[]
used={}
for i in a:
    a0.append(i)
for i in b:
    b0.append(i)
ans=0
q=''.join(' '+str(e) for e in a)
q=q.join(' '+str(e) for e in b)
used[q]=True
while 1:
    x=a[0]
    y=b[0]
    if x>y:
        del a[0]
        del b[0]
        a.append(y)
        a.append(x)
    else:
        del b[0]
        del a[0]
        b.append(x)
        b.append(y)

    ans=ans+1
    if len(a)==0:
        print "{0} 2".format(ans)
        break
    elif len(b)==0:
        print "{0} 1".format(ans)
        break

    q=''.join(' '+str(e) for e in a)
    q=q.join(' '+str(e) for e in b)
    if used.get(q):
        print "-1"
        break

    used[q]=True

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 self.mano[0]>otro_soldado.mano[0]

    def __lt__(self,otro_soldado):
      return self.mano[0]<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)

#ahora hago el juego

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

    elif soldado1==soldado2:
      juego=False

    if t>50:
      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")

# It's never too late to start!
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

# Stay hungry, stay foolish!

def main():
    n = iin()
    k1 = ain()
    k2 = ain()
    d1 = deque(k1[1:])
    d2 = deque(k2[1:])
    k1 = k1[0]
    k2 = k2[0]
    a1 = d1.copy()
    a2 = 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 == a1 or d2 == a2:
            break
    if flag == -1:
        print(flag)
    else:
        print(ans, flag)

# Fast IO Template starts

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")
# Fast IO Template ends
if __name__ == "__main__":
    main()

# Never Give Up - John Cena

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
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
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))
state.add(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)
    # print(s1, s2)
    if not s1:
        out(cnt + 1, 2)
        exit()
    if not s2:
        out(cnt + 1, 1)
        exit()
    if tuple(s1) in state or tuple(s2) in state:
        out(-1)
        exit()
    cnt += 1
    state.add(tuple(s1))
    state.add(tuple(s2))

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 or k2 in memb:
        print(-1)
        break

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>100:
        break
if t>100:
    print(-1)
else:
    if s1:
        print(t, 1)
    else:
        print(t, 2)

import sys

n = int(raw_input())
xcards = map(int, raw_input().split())
x = xcards[0]
xcards = xcards[1:]
y = n - x
ycards = map(int, raw_input().split())[1:]

fights = 0
states = set()
while xcards and ycards:
    fights += 1
    xval = xcards.pop(0)
    yval = ycards.pop(0)
    if xval > yval:
        xcards.append(yval)
        xcards.append(xval)
    else:
        ycards.append(xval)
        ycards.append(yval)

    if tuple(xcards + ycards) in states:
        print -1
        sys.exit(0)
    states.add(tuple(xcards + ycards))
print fights, 1 if xcards else 2

import sys

def solve(da, db):
    da_n = da[:]
    db_n = db[:]
    while True:
        if da[0] < db[0]:
            db.append(da[0])
            db.append(db[0])
        if da[0] > db[0]:
            da.append(db[0])
            da.append(da[0])
        da.pop(0)
        db.pop(0)
        if len(da) == 0:
            return 2
        if len(db) == 0:
            return 1
        if da_n == da:
            return -1

if __name__ == '__main__':
    t = input()
    da = map(int, sys.stdin.readline().rstrip().split())[1:]
    db = map(int, sys.stdin.readline().rstrip().split())[1:]
    print solve(da, db)

n=input()
k1=raw_input().split(' ')
k2=raw_input().split(' ')
k1f=[None]*len(k1)
k2f=[None]*len(k2)
for i in range(len(k1)):
    k1[i]=int(k1[i])
    k1f[i]=k1[i]
for i in range(len(k2)):
    k2[i]=int(k2[i])
    k2f[i]=k2[i]
fight=0
while k1[0]!=0 and k2[0]!=0:
    if k1[1]>k2[1]:
        x=k1[1]
        y=k2[1]
        for i in range(1,len(k1)-1):
            k1[i]=k1[i+1]
        for i in range(1,len(k2)-1):
            k2[i]=k2[i+1]
        k1[len(k1)-1]=y
        k1=k1+[x]
        k2.remove(k2[len(k2)-1])
        fight=fight+1
        k1[0]=len(k1)-1
        k2[0]=len(k2)-1
    else:
        x=k2[1]
        y=k1[1]
        for i in range(1,len(k1)-1):
            k1[i]=k1[i+1]
        for i in range(1,len(k2)-1):
            k2[i]=k2[i+1]
        k2[len(k2)-1]=y
        k2=k2+[x]
        z=k1[len(k1)-1]
        k1.remove(z)
        fight=fight+1
        k1[0]=len(k1)-1
        k2[0]=len(k2)-1
    if k1==k1f and k2==k2f:
        print -1
        break
if k1!=k1f and k2!=k2f:
    if k1[0]==0:
        print fight,2
    else:
        print fight,1

def pick_card(k, stack):
	k -= 1
	devide = 10**k
	card = stack / devide
	stack = stack % devide
	return k, card, stack

def puts_card(k, stack, card_w, card_l):
	k += 2
	return k, stack*100 + card_l*10 + card_w

n = int(raw_input())
inputs = raw_input().split(" ")
k1 = int(inputs[0])
stack1 = int("".join(inputs[1:]))
inputs = raw_input().split(" ")
k2 = int(inputs[0])
stack2 = int("".join(inputs[1:]))
played = set([(stack1,stack2)])
fight = 0

while 1:
	fight += 1
	k1, card1, stack1 = pick_card(k1, stack1)
	k2, card2, stack2 = pick_card(k2, stack2)
	if card1 > card2:
		k1, stack1 = puts_card(k1, stack1, card1, card2)
	else:
		k2, stack2 = puts_card(k2, stack2, card2, card1)

	if k1 == 0:
		print fight, 2
		break
	elif k2 == 0:
		print fight, 1
		break
	elif (stack1, stack2) in played:
		print -1
		break
	else:
		played.add((stack1,stack2))

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 and count<500:
    if s1[0]>s2[0]:
        s1.append(s2[0])
        s1.append(s1[0])
        s1=s1[1:]
        s2=s2[1:]

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

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 (arr1 != start and arr2 != end) or count == 0:
    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())
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[:])
    print(mema)
    print(memb)
    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)
    print(k1)
    print(k2)
    if k1 == []:
        print(r,2)
    elif k2 == []:
        print(r,1)
    if k1 in mema or k2 in memb:
        print(r,-1)
        break

t=input()
first=map(int,raw_input().split())
second=map(int,raw_input().split())
a=first.pop(0)
b=second.pop(0)

dummy_a=list(first)
dummy_b=list(second)
fight=0

if dummy_a[0]>dummy_b[0]:
        dummy_a.append(dummy_b.pop(0))
        dummy_a.append(dummy_a.pop(0))
        a+=1
        b-=1
        fight+=1
else:
        fight+=1
        dummy_b.append(dummy_a.pop(0))
        dummy_b.append(dummy_b.pop(0))
        a-=1
        b+=1
while (a!=0 and b!=0 and ((dummy_a!=first) and (dummy_b!=second))):
    if dummy_a[0]>dummy_b[0]:
        dummy_a.append(dummy_b.pop(0))
        dummy_a.append(dummy_a.pop(0))
        a+=1
        b-=1
        fight+=1
    else:
        fight+=1
        dummy_b.append(dummy_a.pop(0))
        dummy_b.append(dummy_b.pop(0))
        a-=1
        b+=1
if a==0:
    print fight,2
elif b==0:
    print fight,1
else:
    print -1

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 = (k1[0], k2[0])
    if topcomb in combs:
        fights = -1
        break
    combs.add((k1[0], k2[0]))
    fight(k1, k2)
    fights += 1

print(fights, end=' ')
if fights > -1:
    print(1 if k1 else 2)

import sys

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)

if n < 4:
	print(-1)
	sys.exit()

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(len(k2) != 0):
	print(iteration, 2)
if(len(k1) !=0):
	print(iteration, 1)

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
visited = set()
while k1nums and k2nums:
    top1, top2 = k1nums.popleft(), k2nums.popleft()

    if (top1, top2) in visited:
        print(-1)
        flag = 0
        break
    else:
        visited.add((top1, top2))

    if top1 > top2:
        k1nums.append(top2)
        k1nums.append(top1)
    else:
        k2nums.append(top1)
        k2nums.append(top2)

    ng += 1

if flag:
    if not k1nums:
        print(ng, 2)
    else:
        print(ng, 1)

_ = raw_input()
p1 = raw_input().split()
p1.pop(0)
p2 = raw_input().split()
p2.pop(0)
state = []
count = 0
while True:
  key = '.'.join(p1) + '-' + '.'.join(p2)
  if key in state:
    print -1
    break
  elif len(p1) == 0:
    print "{} {}".format(count, 2)
    break
  elif len(p2) == 0:
    print "{} {}".format(count, 1)
    break
  else:
    state.append(key)
    count += 1
    top1 = p1.pop(0)
    top2 = p2.pop(0)
    if top1 > top2:
      p1.extend([top2, top1])
    else:
      p2.extend([top1, top2])

import Queue,math
n = input()
m = math.factorial(n+1)
q1 = Queue.Queue().queue
q2 = Queue.Queue().queue
L = map(int,raw_input().split())
k1 = L[0]
for i in range(1,len(L)):
	q1.append(L[i])
L = map(int,raw_input().split());
k2 = L[0]
for i in range(1,len(L)):
	q2.append(L[i])
ans=0
r1 = [i for i in q1]
r2 = [i for i in q2]
while len(q1)>0 and len(q2)>0:
	if q1[0] > q2[0]:
		q1.append(q2.popleft())
		q1.append(q1.popleft())
	else:
		q2.append(q1.popleft())
		q2.append(q2.popleft())
	f = 1
	for i in q1:
		if i not in r1:
			f = 0
			break
	if f:
		for i in q2:
			if i not in r2:
				f = 0
				break
	if f:
	 	break
	ans+=1
if f:
	print -1
else:
	print ans,
	if len(q1):
		print 1
	else:
		print 2

n = int(input())

x = input().split()
y = input().split()

player_1 = []
player_2 = []
memory = []
aux = []

for card in range(int(x[0])):
    player_1.append(int(x[card + 1]))
    aux.append(int(x[card + 1]))
for card in range(int(y[0])):
    player_2.append(int(y[card + 1]))
memory.append(aux)

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 player_1 in memory:
        condition = True
    if c1 > c2:
        player_1.append(c2)
        player_1.append(c1)
    else:
        player_2.append(c1)
        player_2.append(c2)
    aux = []
    for card in player_1:
        aux.append(card)
    memory.append(aux)
    counter += 1

if not condition:
    answer = str(counter)
    if len(player_1) == 0:
        answer += " 2"
    else:
        answer += " 1"
else:
    answer = "-1"
print(answer)

__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, 1)
elif len(second) == 0:
    print(round, 2)
else:
    print(-1)

from collections import deque

def wars():
    n = int(input())
    cards = input().split()
    tot = int(cards[0])
    aux = tot
    queue1 = deque(int(i) for i in cards[1:])
    queue2 = deque(int(i) for i in input().split()[1:])
    s1,s2 = sum(queue1), sum(queue2)
    if (s1 / 2 == s2 and queue1[0] < queue2[0]) or (s2 / 2 == s1 and queue2[0] < queue1[0]):
        return -1
    battles = set()
    c = 0
    while queue1 and queue2:
        c1 = queue1.popleft()
        c2 = queue2.popleft()
        if (c1, c2) in battles and aux == tot:
            return -1
        c += 1
        battles.add((c1, c2))
        if c1 > c2:
            queue1.append(c2)
            queue1.append(c1)
            aux += 1
        else:
            queue2.append(c1)
            queue2.append(c2)
            aux -= 1
    w = '1' if queue1 else '2'
    return str(c) + ' ' + w

print(wars())

x=int(input())
A=list(map(int,input().split()))
A=A[1:]
#print(A)
D=A
#print(D)
B=list(map(int,input().split()))
B=B[1:]
E=B
C=[]
print(A)
print(B)
count=0
while(1):
	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
		print(A,B)
		state=0
	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
			print(A,B)
	if A==D:
		if B==E:
			state=1000
			break
	if A==E:
		if B==D:
			state=1000
			break
if state==10:
	print (count,2)
if state==100:
	print (count,1)
if state==1000:
	print (-1)

n=input()
s=set()
F=lambda x:str(reduce(lambda a,i:a|1<<i, x, 0))
a=[map(int,raw_input().split())[1:] for _ in range(2)]
G=lambda: F(a[0])+F(a[1])
s.add(G())
cnt=0
while 1:
    cnt+=1
    k=1 if a[0][0]<a[1][0] else 0
    a[k]+=[a[k^1][0], a[k][0]]
    a[k].pop(0)
    a[k^1].pop(0)
    state=G()
    if state in s:
        print -1
        break
    if len(a[0]) in (0,n):
        print cnt, k+1
        break
    s.add(state)

from collections import deque

def checkVisited():
    p1State = 0
    for card in p1:
        p1State = p1State * 10 + card
    p2State = 0
    for card in p2:
        p2State *= p2State * 10 + card
    if (p1State, p2State) not in visited:
        visited.add((p1State, p2State))
        return False
    return True

nCards = int(raw_input())
p1 = deque(map(int, raw_input().split())[1:])
p2 = deque(map(int, raw_input().split())[1:])
visited = set()
checkVisited()
nMoves = 0
while True:
    nMoves += 1
    p1Card = p1.popleft()
    p2Card = p2.popleft()
    if p1Card > p2Card:
        p1.extend((p2Card, p1Card))
    else:
        p2.extend((p1Card, p2Card))
    if not p1 or not p2:
        print nMoves, 1 if not p2 else 2
        break
    if checkVisited():
        print -1
        break

n=int(raw_input())
a=[]
b=[]

z=raw_input().split(' ')
k1=int(z[0])
for i in range(0,k1):
    a.append(z[i+1])

z=raw_input().split(' ')
k2=int(z[0])
for i in range(0,k2):
    b.append(z[i+1])

k=0
while True:
    if k>10000 or len(a)==0 or len(b)==0:
        break
    if a[0]>b[0]:
        a.append(b[0])
        a.append(a[0])
    else:
        b.append(a[0])
        b.append(b[0])
    del(a[0]); del(b[0])
    k+=1

if k>10000:
    print("-1")
else:
    if len(b)==0:
        print(str(k)+" 1")
    else:
        print(str(k)+" 2")

import sys

def solve(da, db):
    da_n = []
    da_n.append(da[:])
    step = 0
    while True:
        step += 1
        if da[0] < db[0]:
            db.append(da[0])
            db.append(db[0])
        if da[0] > db[0]:
            da.append(db[0])
            da.append(da[0])
        da.pop(0)
        db.pop(0)
        if len(da) == 0:
            return str(step)+' '+str(2)
        if len(db) == 0:
            return str(step)+' '+str(1)
        for i in da_n:
            if i == da:
                return -1
        da_n.append(da[:])

if __name__ == '__main__':
    t = input()
    da = map(int, sys.stdin.readline().rstrip().split())[1:]
    db = map(int, sys.stdin.readline().rstrip().split())[1:]
    print solve(da, db)

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)

"""
Author    : raj1307 - Raj Singh
Institute : Jalpaiguri Government Engineering College
Date      : 3.05.19
"""
from __future__ import division, print_function
import itertools,os,sys
#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify, #heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect_left,bisect_right
#from decimal import *,threading

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
else:
    from builtins import str as __str__
    str = lambda x=b'': x if type(x) is bytes else __str__(x).encode()

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        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):
        return self._buffer.read() if self._buffer.tell() else os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b, ptr = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)), self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
            self.newlines += b.count(b'\n') + (not b)
        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)

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b'\r\n')

def print(*args, **kwargs):
    sep, file = kwargs.pop('sep', b' '), 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', b'\n'))
    if kwargs.pop('flush', False):
        file.flush()

def ii(): return int(input())
def si(): return str(input())
def mi():return map(int,input().strip().split(" "))
def li():return list(mi())

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[0]
def sort2(l):return sorted(l, key=getKey)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]
def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p1
    return res
def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

# For getting input from input.txt file
#sys.stdin = open('input.txt', 'r')

# Printing the Output to output.txt file
#sys.stdout = open('output.txt', 'w')

def main():

    n=ii()
    a=li()
    b=li()
    na=a[0]
    nb=b[0]
    a=a[1:]
    b=b[1:]

    m=0
    while(len(a)!=0 and len(b)!=0 and m!=100):

        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]

        m+=1

    if m==100:
        if len(a)==0:
            print(m,2)
        elif len(b)==0:
            print(m,1)
        else:
            print(-1)
    else:
        if len(a)==0:
            print(m,2)
        elif len(b)==0:
            print(m,1)

if __name__ == "__main__":
    main()

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=0,0,0,0,[]
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 in l3:
        c=1
        break
    else:
        l3.append(l1)
if c==0:
    if len(l1)==0:
        print(str(b)+' 2')
    else:
        print(str(b)+' 1')
else:
    print(-1)

import sys
n=input()

l1=raw_input().split()
a=l1[0]
l1=l1[1:]
l2=raw_input().split()
b=l2[0]
l2=l2[1:]

st=""
for e in l1:
    st=st+str(e)

st=st+"a"
for e in l2:
    st=st+str(e)

dic={st:1}

ans=0
ct=1

while ct>-1:

    val1=l1[0]
    val2=l2[0]

    if val1<val2:
        l1=l1[1:]
        a=[val1,val2]
        l2=l2[1:]+a
    else:
        l2=l2[1:]
        a=[val2,val1]
        l1=l1[1:]+a

    if not l1:
        print str(ct)+" 2"
        ct=-2

    if not l2:
        print str(ct)+" 1"
        ct=-2

    st=""
    for e in l1:
        st=st+str(e)
    st=st+"a"
    for e in l2:
        st=st+str(e)

    if st not in dic:
        dic[st]=1
    else:
        print "-1"
        ct=-2
    ct+=1

n = int(input())

q1 = list(map(int, input().split()))[1:]
q2 = list(map(int, input().split()))[1:]

s = set()
while q1 and q2:
    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(1 if q2 else 2)

n=int(raw_input())
l=map(int,raw_input().split())
m=map(int,raw_input().split())
l=l[1:]
m=m[1:]
a=0
p=[[c for c in l]]
#print l
while len(l)>0 and len(m)>0:
    if l[0]>m[0]:
        l=l[1:]+[m[0],l[0]]
        m=m[1:]
        a+=1
        #print l
        if l in p:
            break
        else:
            p.append(l)
    else:
        m=m[1:]+[l[0],m[0]]
        l=l[1:]
        a+=1
        #print l
        if l in p:
            break
        else:
            p.append(l)
if len(l)==0:
    print str(a)+' '+str(2)
elif len(m)==0:
    print str(a)+' '+str(1)
else:
    print -1

n=int(input())
a=list(map(int,input().split()))
k1=a[0]
s1=a[1:]
s3=sorted(s1)
a=list(map(int,input().split()))
k2=a[0]
s2=a[1:]
s4=s2.sort()
flag=0
if s2==s4 and s1==s3:
    flag=1
fights=0
if flag==0:
    while(len(s1)!=0 and len(s2)!=0):
        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 len(s1)==0:
        won=s2
    else :
        won=s1
    print(fights,won,sep=" ")
else:
    print("-1")

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

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 newa==a and newa[0]>newb[0]:
        flag=0
        break
    if newb==b and newa[0]<newb[0]:
        flag=0
        break
    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)

def app(s):
    n = []
    for i in range(len(s)):
        n.append(s[i])
    return n

n = input()
s1 = map(int,raw_input().split())
s2 = map(int,raw_input().split())
del s1[0]
del s2[0]
foo1 = []
foo2 = []

foo1.append(app(s1))
foo2.append(app(s2))
cnt = 1
f = 0
d = 1
while True:
    if s1[0] == s2[0]:
        f = -1
        break
    elif s1[0] > s2[0]:
        s1.append(s2[0])
        s1.append(s1[0])
        del s2[0]
        del s1[0]
    else:
        s2.append(s1[0])
        s2.append(s2[0])
        del s2[0]
        del s1[0]
    # print foo1
    # print foo2
    if s1 in foo1 and s2 in foo2:
        f = -1
        break
    foo1.append(app(s1))
    foo2.append(app(s2))

    d += 1
    cnt += 1
    if len(s2) == 0:
        f = 1
        break
    if len(s1) == 0:
        f = 2
        break
if f == -1:
    print f
if f == 1:
    print cnt,f
if f == 2:
    print cnt,f

if f == -1:
    print f
if f == 1:
    print cnt,f
if f == 2:
    print cnt,f

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):
    print(a,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)

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

    aconf = {tuple(a)}
    i = 1
    while True:
        x, y = a.pop(), b.pop()
        if x > y:
            a.appendleft(y)
            a.appendleft(x)
        else:
            b.appendleft(x)
            b.appendleft(y)

        atuple = tuple(a)
        btuple = tuple(b)
        if atuple in aconf or btuple in aconf:
            print(-1)
            return
        else:
            aconf.add(atuple)
            aconf.add(btuple)

        if not a:
            print(i, 2)
            return

        if not b:
            print(i, 1)
            return

        i += 1

if __name__ == '__main__':
    main()

from copy import deepcopy
n = int(input())
k1 = list(map(int,input().split()))
k2 = list(map(int,input().split()))
n1,n2 = k1.pop(0),k2.pop(0)
a,b = map(deepcopy,[k1,k2])

lib = []
def solve():
    global a,b,lib
    count = 0
    while(a and b):
        lib.append(a)
        count+=1
        if a[0]>b[0]:
            a+=[b.pop(0),a.pop(0)]
        elif a[0]<b[0]:
            b+=[a.pop(0),b.pop(0)]
        else:
            a+=a.pop(0)
            b+=b.pop(0)
        if a in lib:
            print(-1)
            return -1
    print(count,1 if a else 2)
solve()

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 newa==a:
        flag=0
        break
    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)

x=int(input())
A=list(map(int,input().split()))
A=A[1:]
#print(A)
D=A
#print(D)
B=list(map(int,input().split()))
B=B[1:]
E=B
C=[]
print(A)
print(B)
count=0
while(1):
	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
		print(A,B)
		state=0
	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
			print(A,B)
	if A==D:
		if B==E:
			state=1000
			break
	if A==E:
		if B==D:
			state=1000
			break
if state==10:
	print (count,2)
if state==100:
	print (count,1)
if state==1000:
	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 in data:
        print(-1)
        break
    data.append(deepcopy(a))
    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())
list1 = list(map(int, input().split()))
list2 = list(map(int, input().split()))
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+1:
        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()))
t1 = l1[1:]
t2 = l2[1:]
cnt = 0
while cnt<100:
    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=raw_input()
n=int(n)
aa=raw_input().split(' ')
a=[int(i) for i in aa]
bb=raw_input().split(' ')
b=[int(i) for i in bb]
k1=a[0]
k2=b[0]
del a[0]
del b[0]
a0=[]
b0=[]
used={}
for i in a:
    a0.append(i)
for i in b:
    b0.append(i)
ans=0
q=''.join(str(e) for e in a or b)
used[q]=True
while 1:
    x=a[0]
    y=b[0]
    if x>y:
        del a[0]
        del b[0]
        a.append(y)
        a.append(x)
    else:
        del b[0]
        del a[0]
        b.append(x)
        b.append(y)

    ans=ans+1
    if len(a)==0:
        print "{0} 2".format(ans)
        break
    elif len(b)==0:
        print "{0} 1".format(ans)
        break

    q=''.join(str(e) for e in a or b)
    if used.get(q):
        print "-1"
        break

    used[q]=True

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 set(arr1) in seen:
        print(-1)
        break
    seen.append(set(arr1))
    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

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
    a_arrays = [a]
    b_arrays = [b]
    while True:
        a,b = make_step(a,b)
        k += 1
        if (a == []) | (b == []):
            break
        if (a in a_arrays) | (b in b_arrays):
            return -1
        a_arrays.append(a)
        b_arrays.append(a)
    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(raw_input())
a=[]
b=[]

z=raw_input().split(' ')
k1=int(z[0])
for i in range(0,k1):
    a.append(z[i+1])

z=raw_input().split(' ')
k2=int(z[0])
for i in range(0,k2):
    b.append(z[i+1])

k=0
while True:
    if k>100000 or len(a)==0 or len(b)==0:
        break
    if a[0]>b[0]:
        a.append(b[0])
        a.append(a[0])
    else:
        b.append(a[0])
        b.append(b[0])
    del(a[0]); del(b[0])
    k+=1

if k>100000:
    print(-1)
else:
    if len(b)==0:
        print(k,2)
    else:
        print(k,1)

n = int(input())

l = list(map(int , input().split()))[1:]
k = list(map(int , input().split()))[1:]
ans = 0

while(len(l) and len(k)):
    v , s = l[-1] , k[-1]
    l , k = l[:-1] , k[:-1]

    if(v > s):
        l += [s , v]
    else:
        k += [v , s]
    ans += 1

if(len(l) == 0):
    print(ans , 2)
else:
    print(ans , 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(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)

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 tempB==initB:
		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())

l = list(map(int , input().split()))[1::-1]
k = list(map(int , input().split()))[1::-1]
ans = 0

while(len(l) and len(k)):
    v , s = l[-1] , k[-1]
    l , k = l[:-1] , k[:-1]

    if(v > s):
        l += [s , v]
    else:
        k += [v , s]
    ans += 1

if(len(l) == 0):
    print(ans , 2)
else:
    print(ans , 1)

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
visited = set()
while k1nums and k2nums:
    top1, top2 = k1nums.popleft(), k2nums.popleft()

    if (top1, top2) in visited:
        print(-1)
        flag = 0
        break
    else:
        visited.add((top1, top2))

    if top1 > top2:
        k1nums.append(top2)
        k1nums.append(top1)
    else:
        k2nums.append(top1)
        k2nums.append(top2)

    ng += 1

if flag:
    if not k1nums:
        print(ng, 2)
    else:
        print(ng, 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
for i in range(1000):
    if a[i]>b[i]:
        a.append(b[0])
        a.append(a[0])

    if b[i]>a[i]:
        b.append(a[0])
        b.append(b[0])

    cnt+=1
    a.pop(0)
    b.pop(0)
    if i==len(a)-1: #or i==len(b)-1:
        print(cnt,2)
        quit()
    if i==len(b)-1:
        print(cnt,1)
        quit()
if len(a)>0 and len(b)>0:
    print(-1)
else:
    print(cnt)