# 算法导论示例-FastestWay（applet）

832人阅读 评论(0)
/**
* Introduction to Algorithms, Second Edition
* 15.1 Assembly-line scheduling
* @author 土豆爸爸
*
*/
import java.util.ArrayList;
import java.util.List;

public class FastestWay {
public static List<Station> findFastestWay(Assembly a1, Assembly a2) {
assert(a1.stations.size() == a2.stations.size()); //两个装配线长度相同
int n = a1.stations.size();
List<Station> way1 = new ArrayList<Station>(n);
List<Station> way2 = new ArrayList<Station>(n);
a1.stations.get(0).f = a1.e + a1.stations.get(0).a; //计算f(1,1)
a2.stations.get(0).f = a2.e + a2.stations.get(0).a; //计算f(2,1)

for(int j = 1; j < n; j++) {
Station s1 = a1.stations.get(j);    //第1条装配线第j个工位
Station s10 = a1.stations.get(j-1); //第1条装配线第j-1个工位
Station s2 = a2.stations.get(j);    //第2条装配线第j个工位
Station s20 = a2.stations.get(j-1); //第2条装配线第j-1个工位
int t11 = s10.f + s1.a;        //从第1条装配线的j-1工位到第1条装配线j工位所需要时间
int t21 = s20.f + s20.t + s1.a;//从第2条装配线的j-1工位到第1条装配线j工位所需要时间
int t22 = s20.f + s2.a;        //从第1条装配线的j-1工位到第1条装配线j工位所需要时间
int t12 = s10.f + s10.t + s2.a;//从第2条装配线的j-1工位到第1条装配线j工位所需要时间
if(t11 < t21) {
s1.f = t11;
} else {
s1.f = t21;
}

if(t22 < t12) {
s2.f = t22;
} else {
s2.f = t12;
}
}

//出口判断
Station last1 = a1.stations.get(n - 1);
Station last2 = a1.stations.get(n - 1);
if(last1.f + a1.x <= last2.f + a2.x) {
return way1;
} else {
return way2;
}
}
}

/**
* 装配线
*/
class Assembly {
public int e; //上线时间
public int x; //出线时间
public List<Station> stations;

public Assembly(int e, int x) {
this.e = e;
this.x = x;
}
}

/**
* 工位
*/
class Station {
public Assembly assembly;
public int a; //工作时间
public int t; //从上一工位到当前工位的转换时间
public int f; //到达当前工位最短时间
public Station(Assembly assembly, int a, int t) {
this.assembly = assembly;
this.a = a;
this.t = t;
}
}

import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

public class FastestWayTest extends TestCase {
public void testFastestWay() {
Assembly a1 = new Assembly(2, 3);
List<Station> s1 = new ArrayList<Station>();
a1.stations = s1;

Assembly a2 = new Assembly(4, 2);
List<Station> s2 = new ArrayList<Station>();
a2.stations = s2;

int[] answer = {7, 5, 3, 4, 5, 4};
List<Station> way = FastestWay.findFastestWay(a1, a2);

Station prev = way.get(0);
int sum = prev.assembly == a1 ? a1.e : a2.e;
for(int i = 0; i < way.size(); i++) {
Station station = way.get(i);
if(station.assembly == prev.assembly) {
sum += station.a;
} else {
sum += station.a + prev.t;
}
prev = station;
}
sum += prev.assembly == a1 ? a1.x : a2.x;
assertEquals(38, sum);
}
}

0
0

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