INF = 1 << 29
while gets
  l = $_.split.map(&:to_i)
  p = l.shift
  break if p == 0
  dp = Array.new(1001, INF)
  dp[0] = 0
  coins = [1,5,10,50,100,500]
  for i in 0..5
    l[i].times do |k|
      break if (d = coins[i] * (k+1)) > 1000
      (1000-coins[i]).downto(0) do |j|
        if dp[j] != INF 
          dp[j+coins[i]] = dp[j]+ 1
        end
      end
    end
  end
  change = Array.new(1001, INF)
  change[0] = 0
  5.downto(0) do |i|
    (1000/coins[i]).times do |k|
      change[coins[i]*(k+1)] = [change[coins[i]*(k+1)], change[coins[i]*k]+1].min
    end
  end
  change.rotate!(-p)
  p dp[p,1001-p].zip(change[p,1001-p]).map{|v| v[0]+v[1]}.min
end