居然读题读了这么久。。。一直不知道在问什么。。
还是比较简单的,使用一个简单的栈,遇见字母就进栈,遇到“(”不用处理,用到“)”出栈两个元素,计算,然后加到sum上,然后更改行列数再放入栈中,直到字符串结束。
#include<iostream>
#include<map>
#include<stack>
#include<string>
using namespace std;
struct m
{
int a;
int b;
};
map<char,m>mat;
int main()
{
int n;
cin>>n;
while(n--)
{
char ch;
cin>>ch;
cin>>mat[ch].a>>mat[ch].b;
}
stack<m>k;
string s;
while(cin>>s)
{int l;
l=s.length();
// cout<<l<<endl;
int sum=0;
int f=0;
for(int i=0;i<l;i++)
{
char t=s[i];
if(t=='(') continue;
if(t==')')
{
m t1=k.top();
k.pop();
m t2=k.top();
k.pop();
if(t2.b!=t1.a)
{
f=1;
break;
}
sum+=t2.a*t2.b*t1.b;
t2.b=t1.b;
k.push(t2);
}
else
{
m t1=mat[t];
k.push(t1);
}
}
if(f) cout<<"error"<<endl;
else cout<<sum<<endl;
}
}