给定N个工作,其中每个工作都由以下三个元素表示。
1.开始时间
2.完成时间
3.关联的利润或价值
找到与最大利润相关的工作子集,以使子集中没有两个工作重叠。
例子:
Input:
Number of Jobs n = 4
Job Details {Start Time, Finish Time, Profit}
Job 1: {1, 2, 50}
Job 2: {3, 5, 20}
Job 3: {6, 19, 100}
Job 4: {2, 100, 200}
Output:
Jobs involved in maximum profit are
Job 1: {1, 2, 50}
Job 4: {2, 100, 200}
在上一篇文章中,我们讨论了加权作业调度问题。但是,该帖子仅涵盖与获取最大利润有关的代码。在这篇文章中,我们还将打印出获利最大的职位。
令arr [0..n-1]为Jobs的输入数组。我们定义一个数组DP [],以便DP [i]存储要获得最大利润的数组arr [0..i]所涉及的Jobs。即DP [i]存储子问题arr [0..i]的解。其余算法与以前的文章中讨论的相同。
以下是其C++实现–
// C++ program for weighted job scheduling using Dynamic
// Programming and Binary Search
#include
using namespace std;
// A job has start time, finish time and profit.
struct Job
{
int start, finish, profit;
};
// to store subset of jobs
struct weightedJob
{
// vector of Jobs
vector job;
// find profit associated with included Jobs
int value;
};
// A utility function that is used for sorting events
// according to finish time
bool jobComparator(Job s1, Job s2)
{
return (s1.finish < s2.finish);
}
// A Binary Search based function to find the latest job
// (before current job) that doesn't conflict with current
// job. "index" is index of the current job. This function
// returns -1 if all jobs before index conflict with it. The
// array jobs[] is sorted in increasing order of finish time
int latestNonConflict(Job jobs[], int index)
{
// Initialize 'lo' and 'hi' for Binary Search
int lo = 0, hi = index - 1;
// Perform binary Search iteratively
while (lo <= hi)
{
int mid = (lo + hi) / 2;
if (jobs[mid].finish <= jobs[index].start)
{
if (jobs[mid + 1].finish <= jobs[index].start)
lo = mid + 1;
else
return mid;
}
else
hi = mid - 1;
}
return -1;
}
// The main function that finds the subset of jobs
// associated with maximum profit such that no two
// jobs in the subset overlap.
int findMaxProfit(Job arr[], int n)
{
// Sort jobs according to finish time
sort(arr, arr + n, jobComparator);
// Create an array to store solutions of subproblems.
// DP[i] stores the Jobs involved and their total profit
// till arr[i] (including arr[i])
weightedJob DP[n];
// initialize DP[0] to arr[0]
DP[0].value = arr[0].profit;
DP[0].job.push_back(arr[0]);
// Fill entries in DP[] using recursive property
for (int i = 1; i < n; i++)
{
// Find profit including the current job
int inclProf = arr[i].profit;
int l = latestNonConflict(arr, i);
if (l != - 1)
inclProf += DP[l].value;
// Store maximum of including and excluding
if (inclProf > DP[i - 1].value)
{
DP[i].value = inclProf;
// including previous jobs and current job
DP[i].job = DP[l].job;
DP[i].job.push_back(arr[i]);
}
else
// excluding the current job
DP[i] = DP[i - 1];
}
// DP[n - 1] stores the result
cout << "Optimal Jobs for maximum profits are\n" ;
for (int i=0; i
输出:
Optimal Jobs for maximum profits are
(1, 2, 50)
(2, 100, 200)
Total Optimal profit is 250