loop do
    n, m = gets.split.map &:to_i
    break if n == 0
    codes = (1..m).map { gets.to_i }
    xs = (1..n).map { gets.to_i }

    table = [Float::INFINITY] * 256
    table[128] = 0
    xs.each do |x|
        new_table = [Float::INFINITY] * 256
        (0..255).each do |y0|
            d0 = table[y0]
            codes.each do |c|
                y =  y0 + c
                y = 0 if y < 0
                y = 255 if y > 255
                d = d0 + (x - y) ** 2
                new_table[y] = d if d < new_table[y]
            end
        end
        table = new_table
    end
    p table.min
end