您的位置:首页 > 其它

算法导论 ch15 动态规划 任务调度

2010-05-30 11:49 435 查看
1. souce codes

#include <iostream>
using namespace std;
void fastestWay(int a[][6], int t[][5], int e[2], int x[2], int n) {
int f[2][6];
int l[2][6];
int fstar = 0;
int lstar = 0;
f[0][0] = e[0] + a[0][0];
f[1][0] = e[1] + a[1][0];
for (int j = 1; j < n; j++) {
if (f[0][j - 1] + a[0][j]<= f[1][j - 1] + t[1][j-1]+ a[0][j]) {
f[0][j] = f[0][j - 1] + a[0][j];
l[0][j] = 0;
} else {
f[0][j] = f[1][j - 1] + t[1][j-1]+ a[0][j];
l[0][j] = 1;
}
if (f[1][j - 1] + a[1][j]<= f[0][j - 1] + t[0][j-1]+ a[1][j]) {
f[1][j] = f[1][j - 1] + a[1][j];
l[1][j] = 1;
} else {
f[1][j] = f[0][j - 1] + t[0][j-1]+ a[1][j];
l[1][j] = 0;
}
}
if (f[0][n - 1] + x[0]<= f[1][n-1] + x[1]) {
fstar = f[0][n-1] + x[0];
lstar = 0;
} else {
fstar = f[1][n-1] + x[1];
lstar = 1;
}
cout << "fastest way is "<< fstar << ", and line is "<< lstar << endl;
cout << endl;
cout << "the f table is :"<< endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < n; j++) {
cout << f[i][j]<< " ";
}
cout << endl;
}
cout << endl;
cout << "the l table is :"<< endl;
for (int i = 0; i < 2; i++) {
for (int j = 1; j < n; j++) {
cout << l[i][j]<< " ";
}
cout << endl;
}
cout << endl;
cout << "the fastest way is :"<< endl;
int i = lstar;
cout << "line "<< i << ", station "<< n - 1<< endl;
for (int j = n - 1; j >= 1; j--) {
i = l[i][j];
cout << "line "<< i << ", station "<< j - 1<< endl;
}
}
int main() {
// the time for entering line 1 and line 2
int e[2] = { 2, 4 };
// time on line 1 and line 2
int a[2][6] = { { 7, 9, 3, 4, 8, 4 }, { 8, 5, 6, 4, 5, 7 } };
// transfer time on line 1 and line 2
int t[2][5] = { { 2, 3, 1, 3, 4 }, { 2, 1, 2, 2, 1 } };
// exit time on line 1 and line 2
int x[2] = { 3, 2 };
fastestWay(a, t, e, x, 6);
}


2. test result

fastest way is 38, and line is 0
the f table is :
9 18 20 24 32 35
12 16 22 25 30 37
the l table is :
0 1 0 0 1
0 1 0 1 1
the fastest way is :
line 0, station 5
line 1, station 4
line 1, station 3
line 0, station 2
line 1, station 1
line 0, station 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: