an.sort!

bcs.sort!{|a, b| b[1] <=> a[1]}
cs = []
bcs.each{|bc| bc[0].times{ cs << bc[1] } }

0.upto(cs.size - 1) do | i |
  if an[i] < cs[i]
    an[i] = cs[i]
  else
    break
  end
end

sum = 0
an.each{|a| sum += a }
p sum