# 算法导论示例-GreedyActivitySelector

/** * Introduction to Algorithms, Second Edition * 16.1 An activity-selection problem * @author 土豆爸爸 * */ import java.util.ArrayList; import java.util.List; public class GreedyActivitySelector { /** * 活动 */ static class Activity { int start; //开始时间 int finish; //结果时间 public Activity(int start, int finish) { this.start = start; this.finish = finish; } } /** * 求相互兼容的最大子集 * @param activities 按结束时升序排列的活动数组 * @return 相互兼容的最大子集 */ public static List<Activity> select(Activity[] activities) { List<Activity> list = new ArrayList<Activity>(); list.add(activities[0]); //取第1个活动 int i = 0; //记录最后一个被选择的活动的索引 for(int m = 0; m < activities.length; m++) { if(activities[m].start > activities[i].finish) { //取下一个兼容活动 list.add(activities[m]); i = m; } } return list; } } import java.util.List; import junit.framework.TestCase; public class GreedyActivitySelectorTest extends TestCase { public void testGreedyActivitySelector() { GreedyActivitySelector.Activity [] activities = { new GreedyActivitySelector.Activity(1,4), new GreedyActivitySelector.Activity(3,5), new GreedyActivitySelector.Activity(0,6), new GreedyActivitySelector.Activity(5,7), new GreedyActivitySelector.Activity(3,8), new GreedyActivitySelector.Activity(5,9), new GreedyActivitySelector.Activity(6,10), new GreedyActivitySelector.Activity(8,11), new GreedyActivitySelector.Activity(8,12), new GreedyActivitySelector.Activity(2,13), new GreedyActivitySelector.Activity(12,14) }; List<GreedyActivitySelector.Activity> list = GreedyActivitySelector.select(activities); int[] answer = {0, 3, 7, 10}; for(int i = 0; i < list.size(); i++) { GreedyActivitySelector.Activity a = activities[answer[i]]; assertEquals(a, list.get(i)); } } }
• 本文已收录于以下专栏：

举报原因： 您举报文章：算法导论示例-GreedyActivitySelector 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)