Problem description:
Suppose there is a set of n activities E={1,2,…,n}. Each activity requires the use of the same resource, such as a lecture venue, etc., and only one activity can use this resource at the same time. . Each activity i has a start time si that requires the use of the resource and an end time fi, and si < fi. If activity i is selected, it occupies resources within the half-open time interval [si, fi). If the interval [si, fi) and the interval [sj, fj) do not intersect, then activity i and activity j are said to be compatible. That is to say, when si≥fj or sj≥fi, activity i is compatible with activity j. The activity scheduling problem is to select the largest compatible activity sub-set from the given activity set.
.
It can be seen from the figure that there are 11 activities in S. The largest mutually compatible activity subset is: {a1, a4, a8 , a11,} and {a2, a4, a9, a11}.
2. Dynamic programming solution process
(1) Optimal substructure of activity selection problem
Define the sub-problem solution space Sij to be a subset of S, each of which is compatible with each other. That is, each activity starts after ai ends and ends before aj starts.
In order to facilitate discussion and subsequent calculations, add two fictitious activities a0 and an 1, where f0=0, sn 1=∞.
Conclusion: When i≥j, Sij is the empty set.
If activities are ordered monotonically increasing by end time, the subproblem space is used to select the largest compatible subset of activities from Sij, where 0≤i<j≤n 1, so the other Sij are all empty sets.
The optimal substructure is: Assume that the optimal solution Aij of Sij contains activity ak, then for S The solution Aik of ik and the solution Akj of Skj must be optimal.
The problem is divided into two sub-problems through an activity ak. The following formula can calculate the solution Aij of Sij.
(2) A recursive solution
Let c[i][j] be the number of activities in the largest compatible subset of Sij. When Sij is the empty set, c[i][j] =0; when Sij is non-empty, if ak is used in the largest compatible subset of Sij, then the problem Sik The maximum compatible subset of and Skj is also used, so we can get c[i][j] = c[i][k] c[k][j] 1.
When i≥j, Sij must be the empty set, otherwise Sij needs to be calculated according to the formula provided above. If a<🎜 is found >k, then Sij is non-empty (at this time, fi≤sk and fk≤sj), if such ak cannot be found, then Sij is the empty set.
The complete calculation formula of c[i][j] is as follows:
Personal test code:
下面是贪心法的代码: 1 #include
1 #include