def g;gets.split.map &:to_i;end
def f n,p
r=h=[[$a,b=$b],[b,$c],[$c,b],[b,$a]]
n>$m ?-1:$a+b==[]||b+$c==[]?n: (1..4).any?{|w|q,s=h[w-1];q.size>0&&p!=5-w&&q[-1]>(s[-1]||0)&&s<<q.pop&&!((r=f n+1,w)<0&&q<<s.pop)}?r:-1
end
while(_,$m=g)[0]>0
_,*$a=g
_,*$b=g
_,*$c=g
p f(0,0)
end