Algorithm to find the best combination of items under certain constraints

前端 未结 7 1630
长情又很酷
长情又很酷 2021-01-06 14:22

I\'ll try to explain the problem in the math language.
Assume I have a set of items X = {x_1, x_2, ..., x_n}. Each item of X belongs to one of

7条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 14:56

    I have a solution that should be good if my understanding of your question is right: So i begin with what i understand

    each Integer is actually an interval from I1 to I2 and a Set is a 
    combination of such intervals. A Set is correct if none of the intervals 
    are intersecting and Set1>Set2 if the sum of Intervals in S1> sum of Intervals in S2.
    

    So what I would've done in this situation would be somthing on these lines.

    1. While comparing the intervals to determine if they intersect, do this.

      a) Sort the intervals in order of start points

      b) compare the end point of first and start point of consecutive intervals to determine an overlap. Keep an integer named gap, and if start and end of 2 intervals do not overlap increment gap with their difference.

    This will automatically get you the sum of intervals in the set by doing Endpoint(lastI)-Startpoint(firstI) - Gap.

    => If you need just the best, you can take one variable max and keep comparing sets as they come.

    => If you need top5 or something then follow below, otherwise skip.

    1. As soon as you get the sum and the set is correct, add the sum to a "MinHeap" of 5 elements. The first 5 elements will go as it is. Basically you are keeping track of the top 5 elements. When a new set is less that the min of the heap "Do Nothing and ignore this set as it is less that the top 5 sets" , when the set is larger than the min(meaning it is in the top 5) replace the min and sift the element down, keeping the min of top 5 at top. This will always keep the top 5 elements in the heap.

    2. Now that you have the top 5 elements, you can easily determine the best with 5 pops. :)

    Note: If intervals are in random order it will get you into a O(n^2) solution , and each comparison would then again have 4 if statements to check for overlap positions. you can sort the intervals in O(nlogn) and then go through the list once to determine overlap,(nlogn +n = nlogn) while simultaneously getting the top 5 sets. This should improve your performance, and time.

    .

提交回复
热议问题