Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this problem NP-hard?

I'm trying to come up with a reasonable algorithm for this problem:

Let's say you have a bunch of balls. Each ball has at least one color, but can also be multicolored. Each ball also has a number on it. There are also a bunch of boxes which are each only one color. The goal is to maximize the sum of the numbers on the balls in the boxes, and the only rules are:

  • in order to place a ball in a box, it has to at least have the box's color on it
  • you can only put one ball in each box.

For example, you can put a blue and green ball into a blue box or a green box, but not into a red box.

I've come up with a few optimizations that help a lot in terms of running time. For example, you can sort the balls in descending order of point value. Then as you go from highest number to lowest, if the ball only has one color, and there are no other higher-point balls that contain that color, you can put it in that box (and thus remove that box and that ball from the remaining combinations).

I'm just curious is there's some kind of dynamic algorithm for this type of problem, or if it's just the traveling salesman problem in disguise. Would it help if I knew there were at most X colors? Any help is greatly appreciated. Thanks!


Edit - here's a simple example:

Balls:

  • 1 red ball - 5 points
  • 1 blue ball - 3 points
  • 1 green/red ball - 2 points
  • 1 green/blue ball - 4 points
  • 1 red/blue ball - 1 point

Boxes:

  • 1 red
  • 1 blue
  • 1 green

Optimal Solution:

  • red ball in red box
  • blue ball in blue box
  • green/blue ball in green box

    Total value: 12 points (5 + 3 + 4)

like image 1000
Kenny Avatar asked Oct 03 '10 00:10

Kenny


1 Answers

This is a special case of the maximum weight matching problem on a weighted bipartite graph. Construct a graph whose left vertices correspond to balls, whose right vertices correspond to boxes and with the edge joining a ball and a box having weight V where V is the number on the ball if the ball can be placed in the box, and 0 otherwise. Add extra boxes or balls joined to the other side with edges of weight zero until you have the same number of vertices on each side. The assignment you're looking for is determined by the set of edges of nonzero weight in the maximum (total) weight matching in the resulting graph.

The assignment algorithm can be solved in O(n^3) time, where n is here the maximum of the number of balls or boxes, using the Hungarian algorithm. (BTW, I should make the disclaimer that I only mention the Hungarian algorithm because it is the theoretical result I happen to be familiar with and it presumably answers the question in the title of whether the original problem is NP-hard. I have no idea whether it is the best algorithm to use in practice.)

like image 70
Reid Barton Avatar answered Oct 16 '22 00:10

Reid Barton