Advertisement
Guest User

priorityQuest

a guest
Mar 11th, 2021
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. from queue import PriorityQueue
  2.  
  3. # Function to calculate the minimum cost
  4. # required to reach the end of line
  5.  
  6. def minCost(N, K, M, a, b):
  7. flag = 1
  8. d = {}
  9.  
  10. # store index of the station and its respective
  11. # rate of fuel
  12.  
  13. for i in range(M):
  14. d[a[i]] = b[i]
  15.  
  16. """
  17. Two condition to check:
  18.  
  19. 1. If last station is far away such that it cannot
  20. be reached even if full capacity is filled
  21.  
  22. 2. if ith station is far away such that it cannot be reached
  23. even if full capacity is filled (this is done by checking
  24. if the difference of two adjacent element exceeds k)
  25. """
  26.  
  27. if K < N-a[i] and i == M-1:
  28. flag = 0
  29. break
  30.  
  31. if i < M-1 and K < a[i+1] - a[i]:
  32. flag = 0
  33. break
  34.  
  35. if not flag:
  36. print(-1)
  37. return;
  38.  
  39.  
  40.  
  41. # store station index and cost of fuel and
  42. # litres of petrol which is being fueled
  43.  
  44. pq=PriorityQueue()
  45. cost = 0
  46. flag = 0
  47.  
  48. for i in range(N):
  49. # check if station is at current index
  50. if i in d: pq.put([i, d[i], 0])
  51.  
  52. # remove all stations where fuel cannot be pumped
  53. print(pq.queue[-1])
  54. while not pq.empty() and pq.queue[-1][2]==K: pq.get()
  55. # # if no station left to fill fuel
  56. # not possible to reach end
  57. if pq.empty():
  58. flag = 1
  59. break
  60.  
  61. # store best station visited so far
  62. # bestStation = pq.queue[-1]
  63. bestStation = pq.get()
  64.  
  65. cost += bestStation[1]
  66.  
  67. bestStation[2] += 1
  68.  
  69. pq.put(bestStation)
  70.  
  71. if flag:
  72. print(-1)
  73. return;
  74.  
  75. print(cost)
  76.  
  77.  
  78.  
  79.  
  80. # Driver code
  81. if __name__ == "__main__":
  82. """
  83. Test case 1:
  84. N = 10
  85. K = 3
  86. M = 4
  87.  
  88. a = [0, 1, 4, 6]
  89. b = [5, 2, 2, 4]
  90.  
  91. output: -1
  92. """
  93.  
  94. """
  95. Test case 2:
  96. N = 10
  97. K = 10
  98. M = 2
  99.  
  100. a = [0, 1]
  101. b = [5, 2]
  102.  
  103. output: 23
  104. """
  105.  
  106.  
  107.  
  108. N = 10
  109. K = 5
  110. M = 3
  111.  
  112. a = [0, 3, 5]
  113. b = [5, 9, 3]
  114.  
  115. minCost(N, K, M, a, b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement