# 算法导论示例-GreedyActivitySelector

1224人阅读 评论(0)
/** * 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)); } } }
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：138072次
• 积分：2087
• 等级：
• 排名：第18298名
• 原创：62篇
• 转载：0篇
• 译文：4篇
• 评论：47条
评论排行
最新评论