动态规划-矩阵连乘
程序员文章站
2022-07-03 14:28:41
...
using System;
using System.Collections.Generic;
namespace 矩阵连乘
{
class Program
{
public static readonly int Count = 5; //表示连乘矩阵的个数
public static List<int> M = new List<int>(); //用于储存每个矩阵的行数和最后一个矩阵的列数
public static int[,] matrx = new int[Count, Count]; //用于存放计算量
public static int[,] process = new int[Count, Count]; //用于存放计算过程
static void Main(string[] args)
{
//添加每个矩阵的行数和最后一个矩阵的列数
M.Add(3);
M.Add(5);
M.Add(10);
M.Add(8);
M.Add(2);
M.Add(4);
//初始化对角线元素为0
for (int i = 0; i < Count; i++)
{
matrx[i, i] = 0;
process[i, i] = 0;
}
Matrix();
Console.WriteLine("最少运算量为:" + matrx[0, Count - 1]);
DisplayProcess(0, Count - 1);
Console.ReadKey();
}
static void Matrix()
{
for (int z = 2; z <= Count; z++) //相乘矩阵的个数
{
for (int i = 0; i <= Count - z; i++) //i表示存储矩阵的行
{
int j = z + i - 1; //j表示存储矩阵的列
matrx[i, j] = matrx[i + 1, j] + M[i] * M[i + 1] * M[j + 1];
process[i, j] = i; //子问题的最优策略是i
for (int k = i + 1; k < j; k++) //当相乘矩阵的个数大于2的时候 存在多个子情况
{
int temp = matrx[i, k] + matrx[k + 1, j] + M[i] * M[k + 1] * M[j + 1];
if (temp < matrx[i, j])
{
matrx[i, j] = temp;
process[i, j] = k;
}
}
}
}
}
/// <summary>
/// 输出过程
/// </summary>
/// <param name="i">行</param>
/// <param name="j">列</param>
static void DisplayProcess(int i, int j)
{
if (i == j)
{
Console.Write("A[" + (i + 1) + "]");
return;
}
Console.Write("(");
DisplayProcess(i, process[i, j]);
DisplayProcess(process[i, j] + 1, j);
Console.Write(")");
}
}
}