题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19085
#include <iostream>
#include <stack>
using namespace std;
/*************************************************************************************************************
题意:输入n个矩阵的维度和一些矩阵链乘表达式,输出乘法的次数。假定A和m*n的,B是n*p的,
那么AB是m*p的,乘法次数为m*n*p
思路:
1,利用栈模拟,碰到字母入栈,碰到右括号 ')' 出栈两个元素,计算并入栈
2,利用结构体实现矩阵行列两个变量的入栈
3,出栈的同时判断是否满足计算的条件(即 m1.y == m2.x)否则直接退出输出 'error'
4,学到一个技巧。进栈方式
a,利用结构体变量入栈,如 39 行
b,利用结构体的构造函数实现多变量的进栈,如 49 行
*************************************************************************************************************/
struct Node{
int x,y;
Node(int x=0,int y=0) : x(x),y(y) {}
}node[30];
int main()
{
int n;
cin>>n;
for(int i = 1;i <= n;i ++){
string c;
cin>>c;
int k=c[0]-'A';
cin>>node[k].x>>node[k].y;
}
string s;
while(cin>>s){
int flag=1,ans=0;
stack<Node> car;
for(int i = 0;i < s.size();i ++){
if(isalpha(s[i]))
car.push(node[s[i]-'A']);
else if(s[i] == ')'){
Node m2=car.top(); car.pop();
Node m1=car.top(); car.pop();
if(m2.x != m1.y){
flag=0;
break;
}
ans+=m1.x*m1.y*m2.y;
car.push(Node(m1.x,m2.y));
}
}
if(flag)
cout<<ans<<endl;
else
cout<<"error"<<endl;
}
return 0;
}