Advertisement
Guest User

heapqQues

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