(n,m),a,b=$<.map{_1.split.map &:to_i} p (1..n*m).find{a[~-_1%n]==b[~-_1%m]}||-1