import java.util.ArrayList; import java.util.List; public class ActiveSelector { private int[] s= {0,1,3,0,5,3,5,6,8,8,2,12}; //a0 a1..a11活动开始时间数组 private int[] f = {0,4,5,6,7,9,9,10,11,12,14,16}; //a0 a1..a11活动结束时间数组 List<Activity> ls = new ArrayList<Activity>(); //用来存放最优选择的容器 public static void main(String[] args) { new ActiveSelector().start(); } void start() { recursiveActivitySelector(s,f,0,11); print(); } private void print() { System.out.println("最优选择方案:"); for(Activity i:ls) { System.out.print("a"+i.index+":"); //打印最优的选择方案 System.out.println(i.startTime+"-"+i.endTime); } } private void recursiveActivitySelector(int[] s,int[] f,int k,int n) { int m = k + 1; while(m<=n && s[m]<f[k]) { m = m + 1; } if(m <= n) { ls.add(new Activity(s[m],f[m],m)); //将最优的选择加入到容器中 recursiveActivitySelector(s,f,m,n); } } private class Activity { private int startTime = 0; //活动的开始时间 private int endTime = 0; //活动的结束时间 private int index = 0; //构造函数 public Activity(int starttime, int endtime,int index) { this.startTime = starttime; this.endTime = endtime; this.index = index; } } }
运行结果和算法导论上一致:
最优选择方案: a1:1-4 a4:5-7 a8:8-11 a11:12-16
原文地址:http://blog.csdn.net/q389281541/article/details/45398115