Search code examples
algorithmgraphlogicnodesmatching

Is It Possible to Satisfy Everyone?


You are given two sets of nodes, each with the same number of nodes. Set A contains a list of people. Set B contains a list of items. Each person has a preference for any number of items in Set B. If we represent these preferences as connections between the person nodes and item nodes, each node must have at least one connection.

Initially I thought that each person can always get their desired item, but this is not always true, for example something like this may happen:

enter image description here

One thought I had was that as long as there are (set A size + set B size-1) or more connections in the graph, it's always possible to form valid connections. However, I'm having troubles proving the correctness of this. Do you know if this is correct? Or is there a different solution completely?


Solution

  • I would approach this problem the following way:

    • Sort people of A by the number of edges they have (from lower to higher).

    • If a person in A has only one prefered item in B, assign it.

    • When a person in A has more than one prefered item in B, choose the item with the smallest number of people in A that prefer it.

    I'd do this with backtracking.