Java TreeSet进行工作排序问题
给出一个工作数组,每个工作都有一个截止日期和相关的利润(如果工作在截止日期前完成)。如果一次只能安排一项工作,如何使总利润最大化。
举例说明
Input : Four Jobs with following deadlines and profits
JobID Deadline Profit
a 4 20
b 1 10
c 1 40
d 1 30
Output : Following is maximum profit sequence of jobs
c, a
Input : Five Jobs with following deadlines and profits
JobID Deadline Profit
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output : Following is maximum profit sequence of jobs
c, a, e
建议:请先在{IDE}上尝试你的方法,然后再继续解决
下面是用Java中的TreeSet来解决这个问题的一步步算法。
- 将所有的工作按照它们各自的利润以递减的顺序进行排序。
- 创建一个TreeSet并插入所有从0到n-1的整数。
- 遍历工作数组,对于第i个 工作
- 在TreeSet中搜索一个时间段’x’,其最大值小于第 i项工作的最后期限。
- 如果有任何值存在,则将该工作纳入答案,并从TreeSet中删除’x’。
- 否则,检查其余的工作。
下面是上述算法的实现。
import java.io.*;
import java.util.*;
public class Solution {
// Job class
public static class Job {
char id;
int deadline;
int profit;
// Constructor
Job(char id, int deadline, int profit)
{
this.id = id;
this.deadline = deadline;
this.profit = profit;
}
}
public static class Sorted implements Comparator {
// Function to implement comparator
public int compare(Object o1, Object o2)
{
Job j1 = (Job)o1;
Job j2 = (Job)o2;
if (j1.profit != j2.profit)
return j2.profit - j1.profit;
else
return j2.deadline - j1.deadline;
}
}
// Function to print job scheduling
public static void printJobScheduling(Job jobs[], int n)
{
// Creating object of Sorted class
Sorted sorter = new Sorted();
Arrays.sort(jobs, sorter);
// Creating TreeSet Object
TreeSet<Integer> ts = new TreeSet<>();
for (int i = 0; i < n; i++)
ts.add(i);
for (int i = 0; i < n; i++) {
Integer x = ts.floor(jobs[i].deadline - 1);
if (x != null) {
System.out.print(jobs[i].id + " ");
ts.remove(x);
}
}
}
// Driver Code
public static void main(String[] args)
{
int n = 5;
Job[] jobs = new Job[n];
jobs[0] = new Job('a', 2, 100);
jobs[1] = new Job('b', 1, 19);
jobs[2] = new Job('c', 2, 27);
jobs[3] = new Job('d', 1, 25);
jobs[4] = new Job('e', 3, 15);
printJobScheduling(jobs, n);
}
// Contributed by Dipesh Jain (dipesh_jain)
}
时间复杂度 : O(N*log(N))
辅助空间 : O(N)
极客教程