Activity Selection Problem
1) Sort the activities according to their finishing time
2) Select the first activity from the sorted array and print it.
3) Do following for remaining activities in the sorted array.
a) If the start time of this activity is greater than or equal to the finish time of previously selected activity then select this activity and print it.
2) Select the first activity from the sorted array and print it.
3) Do following for remaining activities in the sorted array.
a) If the start time of this activity is greater than or equal to the finish time of previously selected activity then select this activity and print it.
Example:
Consider the following 3 activities sorted by finish time.
Input:
start[] = {10, 12, 20};
finish[] = {20, 25, 30};
Output:
A person can perform at most two activities. The
maximum set of activities that can be executed
is {0, 2}
C program:
#include<stdio.h>
/* Prints a maximum set of activities that can be done by a single person, one at a time.*/
// n --> Total number of activities
// s[] --> An array that contains
//start time of all activities
//start time of all activities
// f[] --> An array that contains
//finish time of all activities
//finish time of all activities
void printMaxActivities(int s[], int f[], int n)
{
int i, j;
printf ("Following activities are selected n ");
i = 0;
printf("%d ", i);
for (j = 1; j < n; j++)
{
// If this activity has start time greater than or
// equal to the finish time of previously selected
// activity, then select it
if (s[j] >= f[i])
{
printf ("%d ", j);
i = j;
}
}
}
int main()
{
int s[] = {1, 3, 0, 5, 8, 5};
int f[] = {2, 4, 6, 7, 9, 9};
int n = sizeof(s)/sizeof(s[0]);
printMaxActivities(s, f, n);
return 0;
}
Output:
Following activities are selected n 0 1 3 4
0 comments:
Post a Comment