在前一节,我们讲到了动态规则问题的一般理论方法。这一节,我将带领大家详解装配站问题
问题描述
见《算法导论》15.1节
对于这个问题,我们应该如何求解呢?
装配站1线和2线上,每条线上有6个小站,每个小站的工作效率也不一样,换一句话说,在装配站1和2线上,相同位置的小站,对同一个零部件,加工所花的时间不一样。我们要找的,就是哪个装配站上的哪个小站的工作效率高,找出工作效率最高的几个小站,就形成了最优的解决方案
问题描述
见《算法导论》15.1节
对于这个问题,我们应该如何求解呢?
装配站1线和2线上,每条线上有6个小站,每个小站的工作效率也不一样,换一句话说,在装配站1和2线上,相同位置的小站,对同一个零部件,加工所花的时间不一样。我们要找的,就是哪个装配站上的哪个小站的工作效率高,找出工作效率最高的几个小站,就形成了最优的解决方案
现在,我们要写一个状态转移方程了。
有了这个状态转移方程,写代码就容易了。
#include <stdio.h>
#include<stdlib.h>
void fasted_way(int (*a)[6], int (*t)[5], int* enter, int* exit, int n, int**f ,int *l)
{
int j;
*(*(f+0) + 0) = *enter + a[0][0];
*(*(f+1) + 0) = *(enter+1) + a[1][0];
for (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 + j -1) = 0;
} else {
*(*(f+0) + j) = *(*(f+1) + j -1) + a[0][j] + t[1][j-1];
*(l + j - 1) = 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 + j - 1) = 1;
} else {
*(*(f+1) + j) = *(*(f+0) + j -1) + a[1][j] + t[0][j-1];
*(l + j - 1) = 0;
}
}
if (f[0][5] + exit[0] <= f[1][5] + exit[1])
{
f[0][5] += exit[0];
*(l + 5) = 0;
} else
{
f[1][5] += exit[1];
*(l + 5) = 1;
}
}
void main()
{
int n = 6;
int enter[2] = {2,4};
int exit[2] = {3,2};
int a[2][6] = {7,9,3,4,8,4,8,5,6,4,5,7};
int t[2][5] = {2,3,1,3,4,2,1,2,2,1};
//total time
int** f = (int**)malloc(sizeof(int*) * 2);
int i;
for (i=0;i<2;i++)
{
*(f+i) = (int*)malloc(sizeof(int) * 6);
}
//map,key is station'num, value is line'num
int* l = (int*)malloc(sizeof(int) * 6);
fasted_way(a, t, enter, exit, n, f,l);
int j;
for (j=5;j>=0;j--)
{
printf("station way= %d,station num=%d\n", j, l[j]);
}
printf("total time=%d\n", f[l[5]][5]);
//release
for (i=0;i<2;i++)
{
free(*(f+i));
}
free(f);
free(l);
}