fork(2) download
  1. def search(m, k)
  2. r = @ratio[k]
  3. return [m, m] unless r
  4. n, q = search(m / r, k + 1)
  5. n1, pay1 = n + m % r, r * q + m % r
  6. n, q = search(-(-m / r), k + 1)
  7. n2, pay2 = n + (-m % r), r * q
  8. n1 < n2 ? [n1, pay1] : [n2, pay2]
  9. end
  10.  
  11. coin = [1, 5, 10, 50, 100, 500, 1000, 5000, 10000]
  12. @ratio = (0..coin.size - 2).map {|i| coin[i + 1] / coin[i]}
  13.  
  14. DATA.each do |d|
  15. m = d.to_i
  16. n, pay = search(m, 0)
  17. puts "M = #{m} -> #{pay}yen, #{n}mai"
  18. end
  19.  
  20. __END__
  21. 110
  22. 555
  23. 9999
Success #stdin #stdout 0.02s 7460KB
stdin
Standard input is empty
stdout
M = 110 -> 110yen, 2mai
M = 555 -> 555yen, 3mai
M = 9999 -> 10000yen, 2mai