###### UVa 442 ------ Matrix Chain Multiplication

如A m*n, B n*p, 那么A*B的步数为m*n*p;若A的列数不等于B的行数，乘法无法进行

若遇到右括号，则取栈顶的两个元素相乘（注意两个矩阵的顺序），累加步数，并将相乘的结果入栈

/*
UVa 442 矩阵链乘
*/
#include <cstdio>
#include <stack>
#include <iostream>
#include <string>
using namespace std;

struct Mat{
int r, c;
Mat(int a = 0, int b = 0)
:r(a), c(b){}
}m[26];

stack<Mat> s;

int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i){
//n个矩阵的存储
string name;
cin >> name;
int k = name[0] - 'A';
cin >> m[k].r >> m[k].c;
}

string tmp;
while (cin >> tmp){
int len = tmp.length();
bool error = false;
int ans = 0;
for (int i = 0; i < len; ++i){
if (isalpha(tmp[i])) //字母，则入栈
s.push(m[tmp[i] - 'A']);
else if (tmp[i] == ')'){
//遇到又括号，k2,k1依次出栈，累加上步数，并将矩阵相乘结果入栈
Mat k2 = s.top(); s.pop();
Mat k1 = s.top(); s.pop();//注意后取的为k1, 运算k1*k2
if (k1.c != k2.r){
error = true;
break;
}
else
{
ans += (k1.r * k1.c * k2.c);
s.push(Mat(k1.r, k2.c));
}
}
}//for(i)
if (error){
printf("error\n");
}
else{
printf("%d\n", ans);
}
}//while(tmp)
return 0;
}

#### UVa442 Matrix Chain Multiplication（矩阵链乘）

2014-08-03 09:14:48

#### UVA 442 - Matrix Chain Multiplication 数据结构专题

2012-07-01 07:16:04

#### UVA_442: Matrix Chain Multiplication

2015-10-07 14:05:25

#### 动态规划 (Dynamic Programming) 之 矩阵链乘法(Matrix Chain Multiplication)

2009-02-27 15:36:00

#### hdu 1082 Matrix Chain Multiplication

2014-01-27 17:11:42

#### Matrix Chain Multiplication（栈的简单应用）

2013-01-12 11:57:39

#### 矩阵链乘法问题描述(Matrix-chain multiplication)

2015-09-13 14:44:32

#### HDU 1082.Matrix Chain Multiplication【栈的应用+矩阵乘法规则】【1月4】

2016-01-04 23:06:25

#### C++作业9.|Matrix chain multiplication

2016-11-29 19:14:59

#### UVA 442 Matrix Chain Multiplication

2013-08-28 19:36:16

## 不良信息举报

UVa 442 ------ Matrix Chain Multiplication