用栈来算一算就可以了。
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<map> using namespace std; struct Mar { int r,c; } mar[300]; int n; char s[3000]; int r,c,top,flag; Mar Stack[300]; int main() { while(~scanf("%d",&n)) { for(int i=0; i<n; i++) { scanf("%s%d%d",s,&r,&c); mar[s[0]-'A'].r=r; mar[s[0]-'A'].c=c; } scanf("%s",s); int len=strlen(s); flag=0; top=-1; for(int i=0; i<len; i++) { if(top==-1) { top++; if(s[i]>='A'&&s[i]<='Z') Stack[top]=mar[s[i]-'A']; else { Mar node; node.c=-1; node.r=-1; Stack[top]=node; } continue; } if(s[i]=='(') { Mar node; node.c=-1; node.r=-1; top++; Stack[top]=node; } else if(s[i]==')') { top--; Stack[top]=Stack[top+1]; if(top-1!=-1&&Stack[top-1].c!=-1&&Stack[top-1].r!=-1) { if(Stack[top-1].c!=Stack[top].r) { flag=-1; break; } else { flag=flag+Stack[top-1].c*Stack[top-1].r*Stack[top].c; Stack[top-1].c=Stack[top].c; top--; } } } else { Mar node; node.c=mar[s[i]-'A'].c; node.r=mar[s[i]-'A'].r; top++; Stack[top]=node; if(Stack[top-1].r!=-1&&Stack[top-1].c!=-1) { if(Stack[top-1].c!=Stack[top].r) { flag=-1; break; } else { flag=flag+Stack[top-1].c*Stack[top-1].r*Stack[top].c; Stack[top-1].c=Stack[top].c; top--; } } } } if(flag==-1) printf("error "); else printf("%d ",flag); } return 0; }