Program to Find Out the Minimum Cost to Purchase All in Python


Suppose, we have N items, which are marked as 0, 1, 2, …, N-1. Then, we are given a 2D list of size S called sets. Here, we can purchase the i-th set for the price sets[i,2], and we receive every item between sets[i, 0] to sets[i, 1]. Also, we have a list of size N called removals, where we can throw away 1 instance of the i-th element for the price removals[i]. So, we have to find out the minimum cost to purchase precisely one of every element from 0 to N-1 inclusive, or the result is -1 if this can't be done.

So, if the input is like sets = [
   [0, 4, 4],
   [0, 5, 12],
   [2, 6, 9],
   [4, 8, 10]
]

removals = [2, 5, 4, 6, 8], then the output will be 4.

To solve this, we will follow these steps −

  • N := size of removals

  • graph := a new matrix for size (N + 1) x (N + 1)

  • for each s, e, w in sets, do

    • add [e+1, w] to graph[s]

  • for each i, r in index i and item r in removals, do

    • add [i, r] to graph[i + 1]

  • pq := a new heap

  • dist := a new map

  • dist[0] := 0

  • while pq is not empty, do

    • d, e := remove the smallest item from heap pq

    • if dist[e] < d is non-zero, then

      • continue the next iteration

    • if e is same as N, then

      • return d

    • for each nei, w in graph[e], do

      • d2 := d + w

      • if d2 < dist[nei] is non-zero, then

        • dist[nei] := d2

        • add [d2, nei] to pq

  • return -1

Example 

Let us see the following implementation to get better understanding −

 Live Demo

import heapq
from collections import defaultdict
class Solution:
   def solve(self, sets, removals):
      N = len(removals)
      graph = [[] for _ in range(N + 1)]
      for s, e, w in sets:
         graph[s].append([e + 1, w])
      for i, r in enumerate(removals):
         graph[i + 1].append([i, r])
      pq = [[0, 0]]
      dist = defaultdict(lambda: float("inf"))
      dist[0] = 0
      while pq:
         d, e = heapq.heappop(pq)
         if dist[e] < d:
            continue
         if e == N:
            return d
         for nei, w in graph[e]:
            d2 = d + w
            if d2 < dist[nei]:
               dist[nei] = d2
               heapq.heappush(pq, [d2, nei])
      return -1

ob = Solution()
print (ob.solve([
   [0, 4, 4],
   [0, 5, 12],
   [2, 6, 9],
   [4, 8, 10]
], [2, 5, 4, 6, 8]))

Input

[[0, 4, 4],
[0, 5, 12],
[2, 6, 9],
[4, 8, 10]], [2, 5, 4, 6, 8]

Output

4

Updated on: 23-Dec-2020

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements