题目:Matrix Chain Multiplication
题意:给n个矩阵的维度,算矩阵链乘表达式
思路:栈操作即可,定义结构体时加个构造方法,存入时直接存!
参考:入门经典-例6-3-P141
代码:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
struct Matrix{
int a,b;
Matrix(int a=0,int b=0):a(a),b(b){}//构造方法
}m[26];
stack<Matrix>s;
int main()
{
int n;
cin >> n;
while(n--)
{
string name;
cin >> name;
int k = name[0] - 'A';
cin >> m[k].a >> m[k].b;
}
string expr;
while(cin >> expr)
{
int len = expr.length();
bool error = false;
int ans = 0;
for(int i=0;i<len;i++)
{
if(isalpha(expr[i]))
s.push(m[expr[i] - 'A']);
else if(expr[i] == ')')
{
Matrix m2 = s.top();s.pop();
Matrix m1 = s.top();s.pop();
if(m1.b != m2.a)
{
error = true;
break;
}
ans += m1.a * m1.b * m2.b;
s.push(Matrix(m1.a,m2.b));
}
}
if(error)
cout << "error\n";
else
cout << ans << endl;
}
return 0;
}