贪心算法作业调度问题Java实现
时间: 2024-06-14 14:03:53 浏览: 109
贪心算法:任务调度问题.doc
```java
import java.util.Arrays;
public class GreedyJobScheduling {
static class Job implements Comparable<Job> {
char id;
int deadline;
int profit;
public Job(char id, int deadline, int profit) {
this.id = id;
this.deadline = deadline;
this.profit = profit;
}
@Override
public int compareTo(Job other) {
return other.profit - this.profit;
}
}
static void printSchedule(Job[] jobs) {
int n = jobs.length;
Arrays.sort(jobs);
int maxDeadline = 0;
for (Job job : jobs) {
if (job.deadline > maxDeadline) {
maxDeadline = job.deadline;
}
}
char[] result = new char[maxDeadline];
boolean[] slot = new boolean[maxDeadline];
for (int i = 0; i < maxDeadline; i++) {
slot[i] = false;
}
for (Job job : jobs) {
for (int j = job.deadline - 1; j >= 0; j--) {
if (!slot[j]) {
result[j] = job.id;
slot[j] = true;
break;
}
}
}
System.out.println("Scheduled jobs: " + new String(result));
}
public static void main(String[] args) {
Job[] jobs = {
new Job('a', 2, 100),
new Job('b', 1, 19),
new Job('c', 2, 27),
new Job('d', 1, 25),
new Job('e', 3, 15)
};
printSchedule(jobs);
}
}
```
阅读全文