算法导论15章装配线实现(c++)


#include "stdafx.h" #include <iostream> #include <math.h> using namespace std; #define N 6 int f1[N] = {0},f2[N] = {0},f_final = 0;//f1数组记录装配线1中某装配站的最小时间,f_final记录完工总时间 int l1[N-1] = {0},l2[N-1] = {0},l_final = 0;//l1数组记录装配线1中某装配站输入从1还是2中来,故值取1或者2,l_final记录最后从x1还是x2完成,每条线第一个站不记录 void Fastest_way (int a[2][N],int e1,int e2,int x1,int x2,int t1[],int t2[])//查找最快装配时间,用f1、f2和l1、12记录 { f1[0] = e1 + a[0][0]; f2[0] = e2 + a[1][0]; for (int j = 1; j < N; j++) { if ( f1[j-1] + a[0][j] <= f2[j-1] + t2[j-1] + a[0][j]) { f1[j] = f1[j-1] + a[0][j]; l1[j-1] = 1; } else { f1[j] = f2[j-1] + t2[j-1] + a[0][j]; l1[j-1] = 2; } if ( f2[j-1] + a[1][j] <= f1[j-1] + t1[j-1] + a[1][j]) { f2[j] = f2[j-1] + a[1][j]; l2[j-1] = 2; } else { f2[j] = f1[j-1] + t1[j-1] + a[1][j]; l2[j-1] = 1; } } if (f1[N-1] + x1 <= f2[N-1] + x2) { f_final = f1[N-1] + x1; l_final = 1; } else { f_final = f2[N-1] + x2; l_final = 2; } } void Print_stations()//逆序查找输出所经过的装配站 { int i = l_final; cout<<"line "<<i<<",station "<<N<<endl; for (int j = N-1; j > 0; j--) { if (i==1) i = l1[j-1]; else i = l2[j-1]; cout<<"line "<<i<<",station "<<j<<endl; } } int main() { int e1 = 2, e2 = 4; int x1 = 3, x2 = 2; int t1[N-1] = {2, 3, 1, 3, 4}; int t2[N-1] = {2, 1, 2, 2, 1}; int a[2][N] = {{7, 9, 3, 4, 8, 4},{8, 5, 6, 4, 5, 7}}; Fastest_way (a, e1, e2, x1, x2, t1, t2); cout<<f_final<<endl; Print_stations(); system("pause"); return 0; }
原文地址:https://www.cnblogs.com/kiss31415926/p/2984707.html