algorithmgreedy

How can i use greedy algorithm to allocate products to stores


I got assigned to solve this problem: Given number of products sold in specific stores, is there a way to find from which stores to buy all products with the condition of buying only one product from each store.

For example if you have stores A,B,C and products a,b,c with each shop selling:

A: a,c

B: a,b,c

C: c

Answer: You will be buying products a from store A product b from store B and product c from store C.

From this am assuming you cant have more products than stores since you are buying just 1 product from each store and you want to buy all of them.

My thought was using a greedy algorithm where you first buy products exclusively sold in one store and solving this hierarchically but it doesn't always work


Solution

  • You could solve it by finding the max-flow on a maximum cardinality matching in a bipartite graph. Construct a source s going to all the stores, {A, B, C}, and draw a directed edge to each product that store has, {a, b, c}. Then the products to the sink, t. Label all edges with 0/1.

    The graph of the example.

    Then apply the greedy Ford–Fulkerson method. If the max-flow reaches the number of stores and the number of products, then one has a viable solution. This will complete in at most O((number of stores, products)✖️(number of edges)), since the maximum capacity is the number of stores and products, and each iteration increases the capacity.