loop do
    n, m = gets.split.map(&:to_i)
    break if n == 0
    codes = (1..m).map { gets.to_i }.sort
    valid_codes = (0..255).map do |x| 
        a = codes.dup
        t = nil 
        t = a.shift until a.empty? || x + a[0] >= 0
        a.unshift t if t
        t = a.pop until a.empty? || x + a[-1] <= 255 
        a << t if t
        a.map{|c| x + c < 0 ? -x : c}.map{|c| x + c > 255 ? 255 - x : c}.uniq
    end 
    xs = (1..n).map { gets.to_i }
    costs = [Float::INFINITY] * 256 
    costs[128] = 0 
    xs.each do |x| 
        new_costs = [Float::INFINITY] * 256 
        (0..255).each do |y0|
            valid_codes[y0].each do |code|  
                y1 = y0 + code
                c = costs[y0] + (y1 - x) ** 2
                new_costs[y1] = c if c < new_costs[y1]
            end
        end
        costs = new_costs
    end 
    p costs.min
end