UVA 442 Matrix Chain Multiplication
题目大意
模拟矩阵链乘的计算,如果出现错误就输出error,否则输出总共的乘法次数
对于一个矩阵\(A(m \times n), B(n \times p)\) 乘法次数为\(m\times n \times p\)
解题思路
这道题目就是经典的表达式模拟,对于一个矩阵的处理,我们可以用map把一个矩阵的名字(字母)映射到一个\(pair,\ pair\)的\(first\)代表矩阵的行数,\(second\)代表矩阵的列数
\(map\)<\(char\), \(pair\)<\(int, int\)> > \(mp\)
就这样处理就好惹
表达式运算规则
遇到字母就把它的行列入栈(栈的类型是\(stack\)<\(pari\)<\(int, int\)>>)
遇到右括号就把栈顶的两个字母都出栈,然后计算这两个矩阵相乘的结果,重新压入栈
这时候可能会问了,这样不会改变矩阵相乘的顺序吗
会,但是没关系,因为矩阵乘法满足结合律,而我们只要求最后的结果
最后别忘记了,矩阵\(A(m \times n), B(n \times p)\)相乘时,如果\(A\)的列数不等于\(B\)的行数
要输出error
坑点
矩阵乘法不满足交换律
先取出来的应该是后面进去的
如果我们要进行矩阵\(A \times B\)运算,从栈中是先取出\(B\)再取出\(A\)的
P.S.
UVa难得有一道输入挺舒服的题
解题代码
#include <iostream>
#include <cstring>
#include <map>
#include <stack>
#define x first
#define y second
using namespace std;
int n, a, b;
char ch;
map<char, pair<int, int> > mp;
int calc(string s)
{
int ans = 0, err = 0;
stack<pair<int, int> > S;
for (auto c : s)
{
if (isalpha(c)) S.push({mp[c].x, mp[c].y});
if (c == ')')
{
auto p = S.top(); S.pop();
auto q = S.top(); S.pop();
if (q.y != p.x) { err = 1; break ; }
ans += q.x * q.y * p.y;
S.push({q.x, p.y});
}
}
return err ? -1 : ans;
}
int main()
{
scanf("%d", &n);
while (n -- )
{
scanf(" %c%d%d", &ch, &a, &b);
mp[ch] = {a, b};
}
string s;
while (cin >> s)
{
int res = calc(s);
if (~res) printf("%d\n", res);
else puts("error");
}
return 0;
}

浙公网安备 33010602011771号