📜  门| GATE-CS-2016(Set 2)|问题17(1)

📅  最后修改于: 2023-12-03 14:58:31.101000             🧑  作者: Mango

GATE-CS-2016(Set 2) Problem 17

Problem Description

Given a list of activities which contain start time, end time, and the room number in which it will take place, there are n activities in total. Two activities can happen in the same room at the same time. The task is to find the minimum number of rooms required such that all the activities can take place without any overlap.

Approach

This problem can be solved by sorting the activities according to their start times and then traversing the list of activities, keeping track of the rooms in which the activities are taking place. If the current activity starts after the previous activity ends, then the same room can be used, otherwise a new room needs to be allocated. The number of rooms needed will be the maximum number of rooms occupied at any point in time.

Algorithm
  1. Create a list of activities.
  2. Sort the activities by start time.
  3. Initialize an empty list of rooms.
  4. For each activity in the sorted list:
    • If the list of rooms is empty, allocate a new room and append the activity to the list of rooms.
    • Otherwise, check if the current activity can be allocated to any one of the existing rooms:
      • If the current activity start time is greater than or equal to the end time of any existing activity in a room, allocate the activity to that room.
      • If no existing room is available, allocate a new room and append the activity to the list of rooms.
  5. Return the size of the list of rooms, which will give the minimum number of rooms needed.
Complexity Analysis

The time complexity of the algorithm is O(nlogn), where n is the number of activities, due to the sorting step. The space complexity is also O(n), as in the worst case scenario, each activity would need its own room.

Code
def min_rooms(activities):
    activities.sort(key=lambda x: x[0]) # Sort by start time
    rooms = []
    for activity in activities:
        allocated = False
        for room in rooms:
            if activity[0] >= room[-1][1]:
                # Allocate to existing room
                room.append(activity)
                allocated = True
                break
        if not allocated:
            # Allocate to new room
            rooms.append([activity])
    return len(rooms)
Conclusion

This problem can be solved by sorting the activities and then traversing the list of activities to keep track of the rooms that are occupied. The time complexity of the algorithm is O(nlogn) due to the sorting step.