問題描述:
貪心算法
package 貪心;
import java.util.*;
public class Greedy2 {
public static void main (String[] args) {
int[] a = {5, 6, 3, 2, 8, 8 ,9};
System.out.println("最優解"+greedy(a,3));
//運行結果
//將機器1從0到9分配給作業7
//將機器2從0到8分配給作業5
//將機器3從0到8分配給作業6
//將機器3從8到14分配給作業2
//將機器2從8到13分配給作業1
//將機器1從9到12分配給作業3
//將機器1從12到14分配給作業4
//最優解14
}
private static int greedy (int[] arr, int m) {
int n = arr.length;
int sum = 0;
if (n <= m) {
for (int i = 0; i < n; i++) {
if (sum < arr[i]) {
sum = arr[i];
}
}
System.out.println("爲每一臺機器分工一個作業");
return sum;
}
List<Job> jobs = new ArrayList<>();
for (int i = 0; i < n; i++) {
Job job = new Job(i + 1, arr[i]);
jobs.add(job);
}
Collections.sort(jobs);
LinkedList<Machine> machines = new LinkedList<>();
for (int i = 1; i <= m; i++) {
Machine machine = new Machine(i, 0);
machines.add(machine);
}
for (int i = 0; i < n; i++) {
Collections.sort(machines);
Machine mac =machines.peek();
System.out.println("將機器" + mac.getId() + "從" + mac.getAvaile() + "到" + (mac.getAvaile() + jobs.get(i).getTime()) + "分配給作業" + jobs.get(i).getId());
int a = mac.getAvaile() + jobs.get(i).getTime();
mac.setAvaile(a);
sum = a;
}
return sum;
}
}
class Job implements Comparable {
private int id;
private int time;
public Job (int id, int time) {
this.id = id;
this.time = time;
}
public int getId () {
return id;
}
public void setId (int id) {
this.id = id;
}
public int getTime () {
return time;
}
public void setTime (int time) {
this.time = time;
}
@Override
public int compareTo (Object o) {
int otherTime = ((Job) o).getTime();
if (this.time < otherTime) return 1;
if (this.time == otherTime) return 0;
return -1;
}
}
class Machine implements Comparable {
private int id;
private int availe;
public Machine (int id, int availe) {
this.id = id;
this.availe = availe;
}
public int getId () {
return id;
}
public void setId (int id) {
this.id = id;
}
public int getAvaile () {
return availe;
}
public void setAvaile (int availe) {
this.availe = availe;
}
@Override
public int compareTo (Object o) {
int otherTime = ((Machine) o).getAvaile();
if (this.availe < otherTime) return -1;
if (this.availe == otherTime) return 0;
return 1;
}
}