#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <map>
#define rep(i,n) for (int i=0;i<n;i++)
#define Max(a,b) a>b?a:b
#define Min(a,b) a<b?a:b
#define INF 0x7fffffff
#define LL long long
using namespace std;
string str;
int n;
typedef pair<int,int> pr;
map<char,pr>m;
void init()
{
m.clear();
for(int i=0;i<n;++i){
char ch;
int row,col;
cin>>ch>>row>>col;
pr tmp(row,col);
m[ch]=tmp;
}
}
int solve()
{
int sum=0;
if(str.size()==1) return 0;
stack<char>st;
map<char,pr>m1(m);
for(int i=0;i<str.size();++i)
{
st.push(str[i]);
bool cal=true;
while(st.size()>1&&cal)
{
cal=false;
char ch1=st.top();
st.pop();
char ch2=st.top();
st.pop();
if(ch1!='('&&ch1!=')'&&ch2!='('&&ch2!=')')
{
if(m1[ch1].first!=m1[ch2].second) return -1;
sum+=m1[ch2].first*m1[ch2].second*m1[ch1].second;
m1[ch2].second=m1[ch1].second;
st.pop();
st.push(ch2);
cal=true;
}
else if(ch1==')'){
st.push(ch2);
cal=true;
}
else
{
st.push(ch2);
st.push(ch1);
}
}
}
return sum;
}
int main()
{
while(cin>>n)
{
init();
while(cin>>str)
{
int ans=solve();
if(ans==-1) puts("error");
else
cout<<ans<<endl;
}
}
return 0;
}
uva 442 Matrix Chain Multiplication
最新推荐文章于 2022-02-24 21:36:00 发布