问题陈述:
我有WareHouses
的列表。 WareHouse
有两个属性,即openingTime
,closingTime
。
public class WareHouse {
private int startTime;
private int endTime;
}
有一组代理商负责将产品交付到仓库,我需要计算可以向所有仓库交付产品所需的最小代理商数量。
假设:当代理商向特定仓库交付产品时,请说W1 {1,2}他只能在1小时的时间内出来,即仓库的关闭时间。
仓库{openingTime,closingTime}
W1 {1,2},{W2 2,4},{W3 3,6},{W4 9,11},{W5 10,11}
public static void main(String[] args) {
WareHouse w1 = new WareHouse(2, 4);
WareHouse w2 = new WareHouse(1, 2);
WareHouse w3 = new WareHouse(3, 6);
WareHouse w4 = new WareHouse(10, 11);
WareHouse w5 = new WareHouse(9, 11);
List<WareHouse> wareHouses = new ArrayList<WareHouse>();
wareHouses.add(w1);
wareHouses.add(w2);
wareHouses.add(w3);
wareHouses.add(w4);
wareHouses.add(w5);
}
理想情况下,它需要2个代理,那么如何为它设计算法?
我的方法:
将有一个后台作业将检查所有代理的状态。一旦代理接收任务,我将其可用性设置为false。一旦完成,我将把他添加回代理队列。但是,我在这里面临的主要挑战是如何猜测代理已完成任务,如何模拟此事件,这将告诉我任务已结束且已经过了2个小时?
答案 0 :(得分:0)
要计算最小代理数,您不需要模拟交付流程。它是一个区间分区问题,您可以使用贪心算法。查看https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pearson/04GreedyAlgorithms-2x2.pdf。
在您的情况下,您可以使用以下代理类(您需要获取Warehouse变量的getter,因为它们是私有的 - 我没有在这里显示):
public class Agent {
int lastFinishTime;
boolean isCompatibleWith(WareHouse x) {
return x.startTime > lastFinishTime;
}
boolean scheduleWareHouse(WareHouse x) {
lastFinishTime = x.endTime;
}
}
然后,您可以按如下方式应用区间分区算法(使用代理的优先级队列,根据lastFinishTime进行排序):
Sort warehouses by starting time so that s1 ≤ s2 ≤ ... ≤ sn.
d ← 0
for j = 1 to n {
if (warehouse j is compatible with some agent k)
schedule warehouse j to agent k
else
allocate a new agent d + 1
schedule warehouse j to agent d + 1
d ← d + 1
}
完成实施:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class Partition {
public static class WareHouse {
int startTime;
int endTime;
public WareHouse(int i, int j) {
startTime=i;
endTime=j;
}
}
public static class Agent {
int end;
public Agent() {
}
public boolean isCompWith(WareHouse x) {
return end <=x.startTime;
}
public void schedule(WareHouse x) {
end=x.endTime;
}
}
public static void main(String...args) {
WareHouse w1 = new WareHouse(2, 4);
WareHouse w2 = new WareHouse(1, 2);
WareHouse w3 = new WareHouse(3, 6);
WareHouse w4 = new WareHouse(10, 11);
WareHouse w5 = new WareHouse(9, 11);
List<WareHouse> wareHouses = new ArrayList<WareHouse>();
wareHouses.add(w1);
wareHouses.add(w2);
wareHouses.add(w3);
wareHouses.add(w4);
wareHouses.add(w5);
Collections.sort(wareHouses, new Comparator<WareHouse> (){
public int compare(WareHouse x, WareHouse y) {
return x.startTime - y.startTime;
}
});
PriorityQueue<Agent> queue =
new PriorityQueue<Agent>(new Comparator<Agent>() {
public int compare(Agent x, Agent y) {
return x.end- y.end;
}
});
for(WareHouse x: wareHouses) {
Agent a = queue.poll();
if(a==null) {
a=new Agent();
a.schedule(x);
queue.add(a);
}
else if (a.isCompWith(x)) {
a.schedule(x);
queue.add(a);
} else {
Agent b = new Agent();
b.schedule(x);
queue.add(a);
queue.add(b);
}
}
System.out.println(queue.size());
}