while true do
  n, m = gets.split.map(&:to_i)
  break if m == 0 && n == 0

  target = []
  3.times do |i|
    nums = gets.split.map(&:to_i)
    nums.shift
    
    nums.each do |num|
      target[num-1] = i
    end
  end


  cnv_target = []
  target.size.times do |i|
    n_odd = 0
    target[0,i].each do |j|
      n_odd += 1 if j.odd?
    end
    cnv = n_odd.even? ? target[i] : 2 - target[i]
    cnv_target << cnv
  end

  count0 = 0
  cnv_target.reverse.each_with_index do |num, i|
    count0 += num * 3**i
  end

  count1 = 3**n - 1 - count0

  count = [count0, count1].min
  puts count > m ? -1 : count
end