Search code examples
greedy

Greedy Algorithm implementation


So I have some questions concerning the solution to the problem of scheduling n activities that may overlap using the least amount of classrooms possible. The solution is below:

Find the smallest number of classrooms to schedule a set of activities S in. To do this efefficiently move through the activities according to starting and finishing times. Maintain two lists of classrooms: Rooms that are busy at time t and rooms that are free at time t. When t is the starting time for some activity schedule this activity to a free room and move the room to the busy list. Similarly, move the room to the free list when the activity stops. Initially start with zero rooms. If there are no rooms in the free list create a new room.

The algorithm can be implemented by sorting the activities. At each start or finish time we can schedule the activities and move the rooms between the lists in constant time. The total time is thus dominated by sorting and is therefore O(n lg n).

My questions are

1) First, how do you move through the activities by both starting and finishing time at the same time?

2) I don't quite understand how it's possible to move the rooms between lists in constant time. If you want to move rooms from the busy list to the free list, don't you have to iterate over all the rooms in the busy list and see which ones have end times that have already passed?

3) Are there any 'state' variables that we need to keep track of while doing this to make it work?


Solution

    1. The way the algorithm works, you need to create a list containing an element for each start time and an element for each end time (so 2n elements in total if there are n activities). Sort this list. When an end time and a start time are equal, sort the end time first -- this will cause back-to-back bookings for halls to work.
    2. If you use linked lists for holding the free and booked halls, you can have the elements you created in step 1 hold pointers back to an activity structure, and this structure can hold a pointer to the list element containing the hall that this activity is assigned to. This will be NULL initially, and will take on a value when that hall is used for that activity. Then when that activity ends, its hall can be looked up in constant time by following two pointers from the activity-end element (first to the activity object, and from there to the hall element).
    3. That should be clear from the above description, hopefully.