Guest User

Untitled

a guest
Apr 26th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. # in Introduction to Algorithms
  2. # Chapter 15, Dynamic Programming, p.329
  3. #
  4. INT_MAX = 2**32
  5.  
  6. $stations = [
  7. [7, 9, 3, 4, 8, 4],
  8. [8, 5, 6, 4, 5, 7]]
  9.  
  10. $enters = [2, 4]
  11. $exits = [3, 2]
  12. $crosses = [
  13. [2, 3, 1, 3, 4],
  14. [2, 1, 2, 2, 1]]
  15.  
  16. $states = [
  17. Array.new($stations[0].size, INT_MAX),
  18. Array.new($stations[1].size, INT_MAX)]
  19.  
  20. def fastest_way
  21. 2.times { |i| $states[i][0] = $enters[i] + $stations[i][0] }
  22.  
  23. 1.upto($stations[0].size-1).each do |i|
  24. # for line 0
  25. 2.times do |j|
  26. $states[0][i] = [$states[0][i], $states[0][i-1] + $stations[0][i]].min # for 0->0
  27. $states[0][i] = [$states[0][i], $states[1][i-1] + $stations[0][i] + $crosses[1][i-1]].min # for 1->0
  28. end
  29.  
  30. # for line 1
  31. 2.times do |j|
  32. $states[1][i] = [$states[1][i], $states[1][i-1] + $stations[1][i]].min # for 1->1
  33. $states[1][i] = [$states[1][i], $states[0][i-1] + $stations[1][i] + $crosses[0][i-1]].min # for 0->1
  34. end
  35. end
  36. [$states[0].last + $exits[0],
  37. $states[1].last + $exits[1]].min
  38.  
  39. end
  40.  
  41. p fastest_way
Add Comment
Please, Sign In to add comment