def cost(m, w)
  (m - w).abs * (((m - w).abs - 30) ** 2)
end

until gets.split.map(&:to_i).all?(&:zero?)
  m = gets.split.map(&:to_i)
  w = gets.split.map(&:to_i)

   dp = Array.new(m.size + 1){Array.new(1 << w.size, 0)}

  m.size.times do |i|
    (1 << w.size).times do |bit|
      w.size.times do |j|
        next if bit[j].zero?
        dp[i][bit] = [dp[i - 1][bit], dp[i][bit], dp[i - 1][bit ^ (1 << j)] + cost(m[i], w[j])].max
      end
    end
  end

  p dp[m.size - 1].max
end