五大常用算法(三) - 贪心算法
贪心算法
简介
贪心算法是指在对问题求解时,总是做出在当前看来是最好的选择。不从整体最优考虑,只做出在某种意义上的局部最优选择。
贪心算法不是对所有问题都能得到整体最优解,但对许多问题它能产生整体最优解。如单源最短路径问题,最小生成树问题等。在一些情况下,即使贪心算法不能得到整体最优解,其最终结果却是最优解的很好近似。由于贪心法的高效性以及其所求得的答案比较接近最优结果,贪心法也可以用作辅助算法或者直接解决一些要求结果不特别精确的问题。
解题的一般步骤是:
1、 建立数学模型来描述问题;
2、把求解的问题分成若干个子问题;
3、 对每一子问题求解,得到子问题的局部最优解;
4、把子问题的局部最优解合成原来问题的一个解。
实例
1. 活动选择问题
有n个需要在同一天使用同一个教室的活动 a1, a2, …, an,教室同一时刻只能由一个活动使用。每个活动 ai 都有一个 开始时间si 和 结束时间fi 。一旦被选择后,活动ai就占据半开时间区间[si,fi)。如果[si,fi]和[sj,fj]互不重叠,ai和aj两个活动就可以被安排在这一天。
该问题就是要安排这些活动使得尽量多的活动能不冲突的举行。例如下图所示的活动集合S,其中各项活动按照结束时间单调递增排序。
贪心策略应该是每次选取结束时间最早的活动。
用贪心法的话思想很简单:活动越早结束,剩余的时间是不是越多?那我就选择最早结束的那个活动,找到后在剩下的活动中再找最早结束的不就得了?这也是把各项活动按照结束时间单调递增排序的原因。
public class ActiveTime {
public static void main(String[] args) {
//创建活动并添加到集合中
List<Active> actives = new ArrayList<Active>();
actives.add(new Active(1, 4));
actives.add(new Active(3, 5));
actives.add(new Active(0, 6));
actives.add(new Active(5, 7));
actives.add(new Active(3, 8));
actives.add(new Active(5, 9));
actives.add(new Active(6, 10));
actives.add(new Active(8, 11));
actives.add(new Active(8, 12));
actives.add(new Active(2, 13));
actives.add(new Active(12, 14));
List<Active> bestActives = getBestActives(actives, 0, 16);
for (int i = 0; i < bestActives.size(); i++) {
System.out.println(bestActives.get(i));
}
}
/**
* @param actives 活动集合
* @param startTime 教室的开始使用时间
* @param endTime 教室的结束使用时间
*/
public static List<Active> getBestActives(List<Active> actives, int startTime, int endTime) {
//最佳活动选择集合
List<Active> bestActives = new ArrayList<Active>();
//将活动按照最早结束时间排序
actives.sort(null);
/**
* 我们记录记录上次活动结束时间nowTime,在结合剩下的活动中,
* 选取开始时间大于nowTime,且结束时间又在范围内的活动,则为下次活动时间,直到选出所有活动
*/
int nowTime = startTime;
for (int i = 0; i < actives.size(); i++) {
Active act = actives.get(i);
if(act.getStartTime()>=nowTime && act.getEndTime()<=endTime){
bestActives.add(act);
nowTime = act.getEndTime();
}
}
return bestActives;
}
}
/**
* 活动类 Active
*/
class Active implements Comparable<Active>{
private int startTime;//活动开始时间
private int endTime;//活动结束时间
public Active(int startTime, int endTime) {
super();
this.startTime = startTime;
this.endTime = endTime;
}
public int getStartTime() { return startTime;}
public void setStartTime(int startTime) { this.startTime = startTime; }
public int getEndTime() { return endTime; }
public void setEndTime(int endTime) { this.endTime = endTime; }
@Override
public String toString() {
return "Active [startTime=" + startTime + ", endTime=" + endTime + "]";
}
//活动排序时按照结束时间升序
@Override
public int compareTo(Active o) {
if(this.endTime > o.getEndTime()){
return 1;
}else if(this.endTime == o.endTime){
return 0;
}else{
return -1;
}
}
}