def f h,r,a,b
$h[[h,r]]||=(*c,(d,e)=a
*c,(d,e)=c until !d||h>d&&r>e
*o,(p,q)=b
*o,(p,q)=o until !p||h>p&&r>q
[d ?f(d,e,c,b)+1:0,p ?f(p,q,a,o)+1:0].max)end
def g;gets.split.map &:to_i;end
while 0<n=g[0]
a=(1..n).map{g}
b=(1..g[0]).map{g}
$h={}
p f 1e3,1e3,a,b
end