Optimize Your Schedule: Activity Selection Using Greedy Approach in C
Discover how to efficiently select the maximum number of non-overlapping activities using the Greedy Algorithm in C.
The Activity Selection Problem is a fundamental problem in combinatorial optimization where the goal is to select the maximum number of activities that don’t overlap, given their start and finish times. In this blog, we will delve into solving this problem using a greedy algorithm in C, complete with a comprehensive explanation and code example.
Implementing the Activity Selection Problem Using a Greedy Approach in C
The greedy approach involves always selecting the next activity that finishes the earliest and is compatible with the previously selected activity. Here’s a complete C program to demonstrate this:
#include<stdio.h>
int st[50], fin[50], c = 0;
void main() {
int i, j, n;
printf("Greedy Approach: Activity Selection >>\n\n");
printf("Enter Number of Activities: ");
scanf("%d", &n);
printf("\nEnter Activity Start time and Finish time Respectively:\n");
for(i = 0; i < n; i++) {
printf("\nStart time for Activity %d: ", 1 + i);
scanf("%d", &st[i]);
printf("Finish time for Activity %d: ", 1 + i);
scanf("%d", &fin[i]);
}
printf("\nSelected Activities are: ");
i = 0;
printf("\n- A%d with %d Start time and %d Finish time", 1, st[0], fin[0]);
for (j = 1; j < n; j++) {
if (st[j] >= fin[i]) {
printf("\n- A%d with %d Start time and %d Finish time", j + 1, st[j], fin[j]);
i = j;
c++;
}
}
printf("\n\nTotal Number of Activities Selected: %d\n", c + 1); // +1 to include the first activity
}Explanation:
1. Variable Initialization:
— `st` and `fin` arrays store the start and finish times of the activities, respectively.
— `c` keeps track of the count of selected activities.
2. Main Function:
— Takes user input for the number of activities and their respective start and finish times.
— Initializes the selection process by always picking the first activity.
— Iterates through the list of activities, selecting each activity that starts after or when the last selected activity finishes.
— Updates the count of selected activities (`c`) and prints each selected activity’s details.
Conclusion
The greedy approach to the Activity Selection Problem provides an efficient and straightforward way to maximize the number of non-overlapping activities you can attend. This C implementation highlights how a simple algorithm can solve complex scheduling problems effectively. By understanding and applying this algorithm, you can improve your ability to tackle similar optimization challenges in various domains. Happy coding
Comments
Post a Comment