I don’t know how to write the title for this question. The existing title may not be precise.
Here is the problem:
I have m groups (arrays), say, 4 groups. Each group contains some numbers. What we wish is that each group gives one number out, and totally the resulting 4 numbers (each from one group) are distinct.
Now given these 4 groups, how can I make sure they fit to our wish?
For example,
A: 0, 2, 3
B: 0, 2
C: 2, 3
D: 1
The above 4 groups can fit to our wish. D gives 1, C gives 3, B gives 2, A give 0.
But if
A: 2
B: 2
C: 2, 3
D: 1
are bad. We can’t let each group give an distinct number.
My idea is the most stupid way that I just do backtrack on all elements from all groups to get every combination of elements and see those elements from one combination are distinct or not.
Anyone has better idea?
You can model this as a network flow problem and then use a fast algorithm in that problem domain (many of which are polynomial time) like Edmunds-Karp or push-relabel.
Create a source node and a sink node. Then create nodes for each “group” and for each distinct element. Connect each group node to the source and each element node to the sink. Finally connect group nodes with element nodes if the group as the element. All flow capacities should be 1.
This is best illustrated with an example. I’ll use the first example you gave:
Will turn into the following flow network:
I couldn’t draw the intermediate flows. But imagine that A flows to 0, 2, 3, and B flows to 0, 2, and C flows to 2, 3, and D flows to 1. All flows are unit capacity.
So first find the max-flow in this graph. The flows between the groups and elements will give you the bipartite matching that you want.
If there isn’t a possible matching, then the max-flow will be less than the number of groups.