分析:利用栈进行简单的表达式求值,遇到右括号,便弹出栈顶的两个元素,看看是否符合矩阵链乘的规则,符合,便进行运算,之后把结果压入栈中;不符合,跳出。
代码如下:
#include <cstdio>
#include <stack>
#include <iostream>
using namespace std;
struct juzhen
{
int a,b;
};
struct juzhen zm[26];
int main()
{
stack<struct juzhen> p;
int t;
scanf("%d",&t);
int tt=t;
getchar();
char ch;
int c,d;
string s;
while (tt--)
{
scanf("%c%d%d",&ch,&c,&d);
getchar();
zm[ch-'A'].a=c;
zm[ch-'A'].b=d;
}
while (cin>>s)
{
int ans=0,f=1;
if (s.length()==1) printf("0\n");
else
{
for (int i=0;i<s.length();i++)
{
if (s[i]=='(') continue;
else if (s[i]==')')
{
struct juzhen a1=p.top(); p.pop();
struct juzhen a2=p.top(); p.pop();
if (a1.a!=a2.b) {f=0;break;}
else
{
ans+=a1.a*a1.b*a2.a;
a1.a=a2.a;
p.push(a1);
}
}
else p.push(zm[s[i]-'A']);
}
if (!f) printf("error\n");
else printf("%d\n",ans);
}
}
return 0;
}