动态规划之装配线问题(递归实现)
装配线问题,问题详见算法导论(第二版)中文版地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];}}}
本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名小橋流水(包含链接)。如您有任何疑问或者授权方面的协商,请给我发邮件。
浙公网安备 33010602011771号