fork download
  1. def f(m, n)
  2. cc = []
  3. count_permutations = ->s, w {
  4. if s < 1 || w < 1
  5. 0
  6. elsif s <= 5 && w == 1
  7. 1
  8. elsif cc[s] && cc[s][w]
  9. cc[s][w]
  10. else
  11. (cc[s] ||= [])[w] = (1..5).inject(0) {|c, d|
  12. c + count_permutations.(s - d, w - 1)
  13. }
  14. end
  15. }
  16. aux = ->acc, b, s, w {
  17. return acc if s < 1 || w < 1
  18. return acc << s if w == 1
  19. (1..5).inject(b) {|b, d|
  20. c = count_permutations.(s - d, w - 1)
  21. return aux.(acc << d, b, s - d, w - 1) if n <= b + c
  22. b + c
  23. } && nil
  24. }
  25. (1..m).inject(0) {|b, w|
  26. c = count_permutations.(m, w)
  27. return aux.([], b, m, w).join.to_i if n <= b + c
  28. b + c
  29. } && 0
  30. end
  31. g = ->m, n {puts "(#{m},#{n}) → #{f(m, n)}"}
  32. g.(2,1)
  33. g.(2,2)
  34. g.(2,3)
  35. g.(20,1)
  36. g.(20,2)
  37. g.(20,3)
  38. g.(20,400096)
  39. g.(20,400097)
  40. g.(32,1)
  41. g.(32,2)
  42. g.(32,3)
  43. g.(32,1000)
  44. g.(32,1000000)
  45. g.(32,1000000000)
  46. g.(32,1333610936)
  47. g.(32,1333610937)
  48.  
Success #stdin #stdout 0.01s 10408KB
stdin
Standard input is empty
stdout
(2,1) → 2
(2,2) → 11
(2,3) → 0
(20,1) → 5555
(20,2) → 14555
(20,3) → 15455
(20,400096) → 11111111111111111111
(20,400097) → 0
(32,1) → 2555555
(32,2) → 3455555
(32,3) → 3545555
(32,1000) → 34355354
(32,1000000) → 11532334334
(32,1000000000) → 2141111311212411131
(32,1333610936) → 11111111111111111111111111111111
(32,1333610937) → 0