|
| 1 | +// C++ program for weighted job scheduling using Naive Recursive Method |
| 2 | +#include<bits/stdc++.h> |
| 3 | +#include <iostream> |
| 4 | +#include <algorithm> |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +// A job has start time, finish time and profit. |
| 8 | +struct Job |
| 9 | +{ |
| 10 | + int start, finish, profit; |
| 11 | +}; |
| 12 | + |
| 13 | +// A utility function that is used for sorting events |
| 14 | +// according to finish time |
| 15 | +bool jobComparataor(Job s1, Job s2) |
| 16 | +{ |
| 17 | + return (s1.finish < s2.finish); |
| 18 | +} |
| 19 | + |
| 20 | +// Find the latest job (in sorted array) that doesn't |
| 21 | +// conflict with the job[i]. If there is no compatible job, |
| 22 | +// then it returns -1. |
| 23 | +int latestNonConflict(Job arr[], int i) |
| 24 | +{ |
| 25 | + for (int j=i-1; j>=0; j--) |
| 26 | + { |
| 27 | + if (arr[j].finish <= arr[i-1].start) |
| 28 | + return j; |
| 29 | + } |
| 30 | + return -1; |
| 31 | +} |
| 32 | + |
| 33 | +// A recursive function that returns the maximum possible |
| 34 | +// profit from given array of jobs. The array of jobs must |
| 35 | +// be sorted according to finish time. |
| 36 | +int findMaxProfitRec(Job arr[], int n) |
| 37 | +{ |
| 38 | + // Base case |
| 39 | + if (n == 1) return arr[n-1].profit; |
| 40 | + |
| 41 | + // Find profit when current job is inclueded |
| 42 | + int inclProf = arr[n-1].profit; |
| 43 | + |
| 44 | + int i = latestNonConflict(arr, n); |
| 45 | + |
| 46 | + if (i != -1) { |
| 47 | + inclProf += findMaxProfitRec(arr, i+1); |
| 48 | + } |
| 49 | + |
| 50 | + // Find profit when current job is excluded |
| 51 | + int exclProf = findMaxProfitRec(arr, n-1); |
| 52 | + |
| 53 | + return max(inclProf, exclProf); |
| 54 | +} |
| 55 | + |
| 56 | +// The main function that returns the maximum possible profit from given array of jobs |
| 57 | + |
| 58 | + |
| 59 | +int findMaxProfit(Job arr[], int n) |
| 60 | +{ |
| 61 | + // Sort jobs according to finish time |
| 62 | + sort(arr, arr+n, jobComparataor); |
| 63 | + |
| 64 | + return findMaxProfitRec(arr, n); |
| 65 | +} |
| 66 | + |
| 67 | + |
| 68 | +// Driver program |
| 69 | +int main() |
| 70 | +{ |
| 71 | + Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}}; |
| 72 | + int n = sizeof(arr)/sizeof(arr[0]); |
| 73 | + cout << "The optimal profit is " << findMaxProfit(arr, n); |
| 74 | + |
| 75 | + return 0; |
| 76 | +} |
0 commit comments