There is n
items, . I have
n
items, but some duplicates and some are missing, I need to have exactly one of each item. There is given a trade-table that tells which items can be traded for others. For example:
Item | Item For |
---|---|
1 | 2 |
2 | 5 |
4 | 3 |
There is infinite stock of trade items in trade-table. But for each trade, you need to pay 1$.
Now we want to know which items to trade so that in the end we have each item exactly once and we minimize needed trades (cost). And if it's not possible then we should detect that it is not possible.
Example:
, we have
and the trade-table is:
.
We need to trade 2x i1 to i2 and 1x i2 to i3.
Solve the problem using max flow min cost algorithm. I'm not in particular interested in time complexity.
How do I construct the graph/flow network?
Such a network needs sources. The sources are the duplicate items. The output from each source has a capacity equal to the number of spares ( count - 1 )
The network needs sinks. The missing items are the sinks. The input to each sink has a capacity if 1
The trade table provides the rest of the links, each with an infinite capacity.
So, for your example,
Apply the Edmonds-Karp algorithm to get your answer https://en.wikipedia.org/wiki/Edmonds%E2%80%93Karp_algorithm Note that is convenient to have just one source and once sink, so connect a common source to all item sources and all the item sinks to a common sink.
The problem is not feasible if the calculated flow into any sink is zero
The total cost is the total calculated flow through the internal links ( all graph links NOT connected to a source or a sink )
FYI here is some C++ code that solves this problem using the above algorithm and the PathFinder graph theory library
Construct the example:
Construct the graph/flow network
Calculate the flows through the graph
Check feasability:
Display required trades
Put this all together and the output is
The complete application code is at https://github.com/JamesBremner/trader