装配线问题,问题详见算法导论(第二版)中文版地193页(英文版323页)。
C#实现如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 动态规划之装配线问题{/// <summary>/// 动态规划之转配线问题,用递归实现,但记录中间结果/// </summary>class Program{static int[,] a = new int[2, 6] { { 7, 9, 3, 4, 8, 4 }, { 8, 5, 6, 4, 5, 7 } };static int[,] t = new int[2, 5] { { 2, 3, 1, 3, 4 }, { 2, 1, 2, 2, 1 } };static int[] e = new int[2] { 2, 4 };static int[] x = new int[2] { 3, 2 };// 两个缓冲区static int[] fa = new int[6] {-1, -1, -1, -1, -1, -1};static int[] fb = new int[6] {-1, -1, -1, -1, -1, -1};/// <summary>/// 主函数/// </summary>/// <param name="args"></param>static void Main(string[] args){Console.WriteLine(f(5));}/// <summary>/// 生产线/// </summary>/// <param name="n"></param>/// <returns></returns>static int f(int n){int ta = f1(n) + x[0];int tb = f2(n) + x[1];return ta < tb ? ta : tb;}/// <summary>/// 第一条生产线/// </summary>/// <param name="j"></param>/// <returns></returns>static int f1(int j){if (fa[j] == -1){if (j == 0)fa[j] = e[0] + a[0, 0];else{int ta = f1(j - 1) + a[0, j];int tb = f2(j - 1) + t[1, j - 1] + a[0, j];fa[j] = ta < tb ? ta : tb;}}return fa[j];}/// <summary>/// 第二条生产线/// </summary>/// <param name="j"></param>/// <returns></returns>static int f2(int j){if (fb[j] == -1){if (j == 0)fb[j] = e[1] + a[1, 0];else{int ta = f2(j - 1) + a[1, j];int tb = f1(j - 1) + t[0, j - 1] + a[1, j];fb[j] = ta < tb ? ta : tb;}}return fb[j];}}}