Memorandum algorithm Matrix Chain issues

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ALPS233/article/details/102662416

Two common algorithms even thinking matrix multiplication:

  1. Interval dynamic programming (bottom-up calculation of optimal substructure)
  2. Memorandum algorithm (topdown)

Times memory recursive search step:
Here Insert Picture Description
m [i] [j] i optimal recording results to j, is initialized to 1;

//min_matrix_OP_beiwanglu 

#include <iostream> 
#include <stdio.h>
#include <string.h>

#define maxn 1005

using namespace std;

int m[maxn][maxn];
int n = 10;
//int a[maxn];
int a[10 + 1] ={5,4,2,6,10,7,3,8,2,9,3};    //10 matrix sample
void init()
{
	memset(m,-1,sizeof(m));	
}

int dfs(int x,int y)
{
	if(m[x][y] >= 0) return m[x][y];
	if(x == y) return m[x][y] = 0;
	
	int tmp = (int)1e9 + 7; 
	for(int k = x; k < y; k++)
		tmp = min(tmp, dfs(x,k) + dfs(k+1,y) + a[x-1] * a[k] * a[y]);
	return m[x][y] = tmp;
	
}

int main()
{
	init();
	cout<<"a[10 + 1] ={5,4,2,6,10,7,3,8,2,9,3}; 10 matrix sample as in Mi.x = a[i-1],Mi.y = a[i]"<<endl; 
	cout<<"result is "<<dfs(1,n)<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/ALPS233/article/details/102662416