算法导论-装配线调度问题
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /*
2 There are 2 lines, each line has 5 station.
3 Pass only one station per line, from left to right.
4 Find the fastest way from enter to exit.
5 Dynamic Programming
6 */
7
8 //enter price per line
9 int e[]={2,4};
10
11 //exit price per line
12 int x[]={3,6};
13
14 //price per station
15 int a[2][5]={7,9,3,4,8,
16 8,5,6,4,5};
17
18 //price when switch station crossing line
19 //switch station in one line need no price
20 int t[2][4]={2,3,1,3,
21 2,1,2,2};
22
23 //the lowest price when arriving a station
24 int f[2][5];
25
26 //n stations each line
27 int n=5;
28
29 //the lowest price
30 int _f;
31
32 //when arriving at a station at the lowest price, which is the last station you pass, just store the line number
33 int l[2][4];
34
35 //which station you will pass just before exit
36 int _l;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 void Fastest_Way()
2 {
3 //there is only one way to get to the first station in each line
4 f[0][0]=e[0]+a[0][0];
5 f[1][0]=e[1]+a[1][0];
6
7 //two way to get to the i's station, we will choose the lower one.
8 for(int i=1;i<n;++i)
9 {
10 if(f[0][i-1]+a[0][i]<f[1][i-1]+t[1][i-1]+a[0][i])
11 {
12 f[0][i]=f[0][i-1]+a[0][i];
13 l[0][i]=0;
14 }
15 else
16 {
17 f[0][i]=f[1][i-1]+t[1][i-1]+a[0][i];
18 l[0][i]=1;
19 }
20
21 if(f[1][i-1]+a[1][i]<f[0][i-1]+t[0][i-1]+a[1][i])
22 {
23 f[1][i]=f[1][i-1]+a[1][i];
24 l[1][i]=1;
25 }
26 else
27 {
28 f[1][i]=f[0][i-1]+t[0][i-1]+a[1][i];
29 l[1][i]=0;
30 }
31 }
32 //when passing the last station, we should add the exit price, the lower will be the fastest
33 if(f[0][n-1]+x[0]<f[1][n-1]+x[1])
34 {
35 _f=f[0][n-1]+x[0];
36 _l=0;
37 }
38 else
39 {
40 _f=f[1][n-1]+x[1];
41 _l=1;
42 }
43 cout <<"The fastest time is "<<_f<<endl;
44
45 //get the full path backward, using a stack is a good way
46 stack<int> s;
47 s.push(_l);
48 for(int i=n-1;i>=1;--i)
49 {
50 s.push(l[_l][i]);
51 _l=l[_l][i];
52 }
53 cout <<"The fastest path is: ";
54 for(int i=0;i<n;++i)
55 {
56 cout <<"S"<<"["<<s.top()+1<<"]"<<"["<<i+1<<"]";
57 if(i!=n-1)
58 cout <<"->";
59 s.pop();
60 }
61 cout <<endl;
62 }