参照《算法导论(第二版)》15.1 节,用C++写的代码。
发现其实写代码不难,但是要理解这个算法,还是要花点时间的。而且,书中的伪代码确实写的精简,20多行的伪代码,愣是被我写出了100多行C++代码。
#include <iostream>
using namespace std;
const int numOfLines = 2; //装配线条数
const int numOfStationsOnEachLine = 6; //每条装配线上的装配站数量
const int arraySizeOfLines = numOfLines + 1; //为了让装配线数字 和 数组下标对应上,这里加1.
const int arraySizeOfStations = numOfStationsOnEachLine + 1; //为了让 装配站编号, 与 数组下标对应上,这里加1.
void fastestWay(int a[arraySizeOfLines][arraySizeOfStations], int t[arraySizeOfLines][arraySizeOfStations-1],
int e[arraySizeOfLines], int x[arraySizeOfLines], const int n,
int &fStar, int f[arraySizeOfLines][arraySizeOfStations], //后面这四个作为输出
int &lStar, int l[arraySizeOfLines][arraySizeOfStations])
{
f[1][1] = e[1] + a[1][1];
f[2][1] = e[2] + a[2][1];
//从装配站2开始,计算f值和l值
for (int j = 2; j <= n; j++)
{
int cost1To1 = f[1][j-1] + a[1][j];
int cost2To1 = f[2][j-1] + t[2][j-1] + a[1][j];
if ( cost1To1 <= cost2To1 )
{
f[1][j] = cost1To1;
l[1][j] = 1;
}
else
{
f[1][j] = cost2To1;
l[1][j] = 2;
}
int cost2To2 = f[2][j-1] + a[2][j];
int cost1To2 = f[1][j-1] + t[1][j-1] + a[2][j];
if (cost2To2 <= cost1To2)
{
f[2][j] = cost2To2;
l[2][j] = 2;
}
else
{
f[2][j] = cost1To2;
l[2][j] = 1;
}
}
int cost1Exit = f[1][n] + x[1];
int cost2Exit = f[2][n] + x[2];
if (cost1Exit <= cost2Exit)
{
fStar = cost1Exit;
lStar = 1;
}
else
{
fStar = cost2Exit;
lStar = 2;
}
}
void printStations(int l[arraySizeOfLines][arraySizeOfStations], int lStar, int n)
{
int i = lStar;
cout << "line " << i << ',' << "station " << n << endl;
for (int j = n; j >= 2; j--)
{
i = l[i][j];
cout << "line " << i << ',' << "station " << j-1 << endl;
}
}
int main(int argc, char** argv)
{
//构建a, t, e, x四个数组
int e[arraySizeOfLines] = {0, 2, 4}; //e[1]表示装配线1的进入时间消耗, e[2]表示装配线2的进入时间消耗
int x[arraySizeOfLines] = {0, 3, 2}; //x[1]表示装配线1的退出时间消耗, x[2]表示装配线2的退出时间消耗
int a[arraySizeOfLines][arraySizeOfStations] = {
{0, 0, 0, 0, 0, 0, 0},
{0, 7, 9, 3, 4, 8, 4}, //装配线1上的每个装配站的时间消耗
{0, 8, 5, 6, 4, 5, 7} }; //装配线2上的每个装配站的时间消耗
int t[arraySizeOfLines][arraySizeOfStations-1] = { //最后一个装配站没有转移消耗,所以-1.
{0, 0, 0, 0, 0, 0},
{0, 2, 3, 1, 3, 4}, //将装配线1上的东西,从每个装配站上移走,需要的时间消耗。由于装配站6移走,就是退出了,所以没有装配站6.
{0, 2, 1, 2, 2, 1} //将装配线2上的东西,从每个装配站上移走,需要的时间消耗。
};
//写出fastestWay函数,输入为a,t,e,x,n,输出为f*, l*,f[i]数组, l[i]数组, 其中,i可取装配线的个数。
//用来保存结果的
int fStar = 0;
int lStar = 0;
int f[arraySizeOfLines][arraySizeOfStations] = {0};
int l[arraySizeOfLines][arraySizeOfStations] = {0};
fastestWay(a, t, e, x, numOfStationsOnEachLine, fStar, f, lStar, l);
//构造通过工厂的最快路线
printStations(l, lStar, numOfStationsOnEachLine);
return 0;
}