def solve(i,cur,c,x,dp)
    return dp if i == x.size
    c.each do |cc|
        num = cur + cc
        num = 0 if num < 0
        num = 255 if num > 255
        if dp[[i,cur]] + (x[i] - num)**2 <= dp[[i+1,num]]
            dp[[i+1,num]] = dp[[i,cur]] + (x[i] - num)**2 
            dp = solve(i+1,num,c,x,dp)
        end
    end
    return dp
end

loop do
    n, m = gets.split.map(&:to_i)
    break if n == 0 && m == 0
    c = m.times.map{gets.to_i}
    x = n.times.map{gets.to_i}
    dp = Hash.new(Float::INFINITY)
    dp[[0,128]] = 0
    dp = solve(0,128,c,x,dp)
    p dp.select{|k,v| k[0] == n}.values.min
end