读懂题意,模拟一下栈处理就行了,数据结构课后习题。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
struct matrix
{
int r;
int c;
};
matrix l,r,t;
stack<matrix> s;
int main()
{
int n,i,j,t1,t2,ans;
bool flag;
matrix m[30],ts,tts;
l.r=-1;
r.r=-2;
char tc,str[12000];
scanf("%d",&n);
getchar();
for (i=0; i<n; i++)
{
scanf("%c%d%d",&tc,&t1,&t2);
getchar();
m[tc-'A'].r=t1;
m[tc-'A'].c=t2;
}
while (1)
{
gets(str);
flag=true;
ans=0;
if (strcmp(str,"") == 0)
break;
while (!s.empty())
s.pop();
for (i=0; str[i]; i++)
{
if (str[i] == '(')
{
s.push(l);
}
else if (str[i] == ')')
{
ts=s.top();
s.pop();
tts=s.top();
s.pop();
if (ts.r != -1 && tts.r != -1)
{
if (ts.r != tts.c)
{
flag=false;
printf("error\n");
break;
}
ans+=tts.r*ts.r*ts.c;
t.r=tts.r;
t.c=ts.c;
s.pop();
s.push(t);
}
else if (tts.r == -1)
{
s.push(ts);
}
}
else
{
s.push(m[str[i]-'A']);
}
}
if (flag)
printf("%d\n",ans);
}
}