using
System;
using
System.Collections.Generic;
public
class
WeightedJobScheduling
{
class
Job {
public
int
start, finish, profit;
public
Job(
int
start,
int
finish,
int
profit)
{
this
.start = start;
this
.finish = finish;
this
.profit = profit;
}
}
class
weightedJob
{
public
List<Job> job;
public
int
value;
public
weightedJob() { job =
new
List<Job>(); }
}
class
JobComparator : IComparer<Job> {
public
int
Compare(Job j1, Job j2)
{
return
j1.finish - j2.finish;
}
}
static
int
latestNonConflict(Job[] jobs,
int
index)
{
int
lo = 0, hi = index - 1;
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;
}
static
int
findMaxProfit(Job[] arr)
{
Array.Sort(arr,
new
JobComparator());
weightedJob[] DP =
new
weightedJob[arr.Length];
DP[0] =
new
weightedJob();
DP[0].value = arr[0].profit;
DP[0].job.Add(arr[0]);
for
(
int
i = 1; i < arr.Length; i++)
{
int
inclProf = arr[i].profit;
int
l = latestNonConflict(arr, i);
if
(l != -1) {
inclProf += DP[l].value;
}
if
(inclProf > DP[i - 1].value) {
DP[i] =
new
weightedJob();
DP[i].value = inclProf;
DP[i].job.AddRange(DP[l].job);
DP[i].job.Add(arr[i]);
}
else
{
DP[i] = DP[i - 1];
}
}
Console.WriteLine(
"Optimal Jobs for maximum profits are"
);
foreach
(Job j
in
DP[arr.Length - 1].job)
{
Console.WriteLine(
"("
+ j.start +
", "
+ j.finish +
", "
+ j.profit
+
")"
);
}
Console.WriteLine(
"\nTotal Optimal profit is "
+ DP[arr.Length - 1].value);
return
DP[arr.Length - 1].value;
}
static
void
Main(
string
[] args)
{
Job[] arr
= {
new
Job(3, 5, 20),
new
Job(1, 2, 50),
new
Job(6, 19, 100),
new
Job(2, 100, 200) };
findMaxProfit(arr);
}
}