Activity selection greedy approach (modified) [dup

2019-05-22 20:47发布

Possible Duplicate:
Algorithm to find the maximum sum in a sequence of overlapping intervals

I was solving the following modified activity scheduling (Greedy approach) problem :

Given a set S of n activities with and start time, Si and fi, finish time of an ith activity. Also given weight wi ,the cost earned by Foo for doing ith activities.

The problem is to select the activities that maximizes foo earnings. We have to return the maximum cost that can be earn by foo.Assume that Foo can only work on a single activity at a time.

Note::

This is similar to classic Activity selection problem ,here the only difference is ,for each activities ,we are given a cost wi . And the goal here is too different -Instead of finding maximum size set of mutually compatible activities ,In this problem we have to find set of those activities that maximise foo total earnings .

Example

Total activities N=4
Si fi wi
0 1 4000
2 5 100
1 4 3000
4 5 2500

Max earning=9500 (Answer)

How do i modify the classical greedy activity selection algorithm ,for solving this problem . What logic should i use to solve the above problem?

1条回答
Luminary・发光体
2楼-- · 2019-05-22 21:33

I don't see how to solve this greedily. The solution I can see is dynamic programming, in which you have to solve the subproblem

F(n) = what is the maximum profit that Foo can get by working only after day n?

Then the recursive formulation is clear: We have that F(n) is either equal to F(n+1) (in the case in which Foo doesn't work on day n), or equal to the maximum out of F(fi) + wi, for each activity that starts on time si=n .

EDIT: Suppose the ending times of the activities are f0 <= f1 <= f2 <= ... <= fN. Then the answer is F[f0] (what is the best profit working starting on time f0), and it can be calculated as:

for n = N to 0:
    F[fn] = F[fn+1]
    for each activity (si, fi, wi):
         if si == fn: 
             F[fn] = max(F[fn], F[fi] + wi)

If the activities are sorted in non-increasing order based on their starting time, the complexity of this approach is linear in the number of activities (as you can stop the inner loop when si < N).

查看更多
登录 后发表回答