Matrix chain multiplication problem

来源:互联网 发布:蓝魅网络lanmeiwl 编辑:程序博客网 时间:2024/06/11 17:54

A good example of dynamic programming is an algorithm that solves the problem of matrix-chain multiplication. We are given a sequence (chain) A1, A2, ..., An of n matrices to be multiplied, and we wish to compute the product A1 A2... An.

 

#include<iostream>
#include
<fstream>
#include
<sstream>
#include
<string>

#define MAX 99999

using namespace std;

int s[100][100];//s[i][j]记录Ai..Aj中分割位置
void print(int i,int j)
{
    
if(i == j)
        cout 
<< 'A' << i;
    
else
    
{
        cout 
<<'(';
        print(i,s[i][j]);
        print(s[i][j]
+1,j);
        cout 
<< ')';
    }

}



int main()
{
    
int p[100];//记录维度,从下标0开始
    int len=-1;//记录p已用位置
    int m[100][100];//m[i][j]表示矩阵Ai..Aj所做乘运算最少的数目


    
string str;
    
int tmp;
    ifstream cin(
"1.txt");
    
while(getline(cin,str))//一次处理一个实例
    {
        istringstream stream(str);
        
while(stream >> tmp)
        
{
            p[
++len] = tmp;
        }

        
for(int i = 1; i <= len; i++)
            m[i][i] 
= 0;

        
for( i = 0; i <= len; i++)
            cout 
<< p[i] << "  ";
        cout 
<<len<<endl;
        
int j,k;
        
int q;

        
for(int l = 2; l <= len; l++)//for1,l is the chain length
        {
            
for(i = 1; i <= len-l+1; i++)//for2,
            {
                j 
= i + l - 1;
                m[i][j] 
= MAX;
                
for(k = i; k <= j-1; k++)//for3
                {
                    q 
= m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
                    
if(q < m[i][j])
                    
{
                        m[i][j] 
= q;
                        s[i][j] 
= k;
                    }

                }
//for3
            }
//for2
        }
//for1

        print( 
1,len);
        cout 
<< endl;
        len 
= -1;
    }
//while

    
return 0;
}
原创粉丝点击