Problem = Struct.new(:cup_count, :swap_limit, :trays) do
  def solve
    steps = dive(0, trays)[0]
    p steps > swap_limit ? -1 : steps
  end
  
  private
  
  def dive(swap_count, trays)
    # p [:dive, swap_count, trays]
    
    if swap_count > swap_limit
      return swap_count, trays
    end
  
    lesser, max = lesser_and_max(trays)
    lesser == max and raise "assertion failed: lesser != max"
    max.nil? and raise "assertion failed: !max.nil?"
    
    if lesser.nil?
      if max == 1
        count, moved = move(max, 0, trays)
        return count + swap_count, trays
      else
        return swap_count, trays
      end
    end
  
    other = ([0, 1, 2] - [max, lesser])[0]
    
    if max == 1
      c1, t1 = move(max, other, trays)
      c2, t2 = move(lesser, max, t1)
      way1 = dive swap_count + c1 + c2, t2
      
      c3, t3 = move(max, lesser, trays)
      way2 = dive swap_count + c3, t3
      
      if way1[0] < way2[0]
        way1
      else
        way2
      end
    else
      c1, t1 = move1(lesser, other, trays)
      c2, t2 = move(max, other, t1)
      way1 = dive swap_count + c1 + c2, t2
      
      c3, t3 = move(max, lesser, trays)
      way2 = dive swap_count + c3, t3
      
      if way1[0] < way2[0]
        way1
      else
        way2
      end
    end
  end
  
  def lesser_and_max(trays)
    trays.each_with_index.
      sort_by {|t,i| t.last || -1 }[1..-1].
      map {|x,i| i unless x.empty? }
  end
  
  def move1(from, to, trays)
    # p [:move1, from, to, trays]
    from != to or raise "source and trays must differ"
    
    trays = trays.dup
    trays[to] = trays[to].dup.push trays[from].last
    trays[from] = trays[from][0..-2]
    
    steps = to == 1 || from == 1 ? 1 : 2
    
    return steps, trays
  end
  
  def move(from, to, trays)
    # p [:move, from, to, trays]
    from != to or raise "source and trays must differ"
    
    from_tray = trays[from]
    
    from_tray.empty? and raise "The source tray must not be empty"
    
    if from_tray.size == 1
      return *move1(from, to, trays)
    end
    
    i = from_tray.size - 1
    while from_tray[i - 1] == from_tray[i] - 1
      i -= 1
    end
  
    trays = trays.dup
    trays[to] = trays[to] + from_tray[i..-1]
    trays[from] = trays[from][0...i]
    
    steps = 3 ** (from_tray.size - i) - 1
    steps /= 2 if to == 1 || from == 1
    
    return steps, trays
  end
end

def input
  STDIN.gets.split.map &:to_i
end

while true
  n, m = input
  break if n == 0 && m == 0
  trays = Array.new(3) { input[1..-1] }
  Problem.new(n, m, trays).solve
end