【链接】 我是链接,点我呀:)
【题意】
【题解】
用栈来处理一下表达式就好。 因为括号是一定匹配的。所以简单很多。 a*b x b*c会做a*b*c次乘法。【代码】
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 26;
int n;
char s[5];
pair <ll, ll> v[300],v1[300];
stack <char> sta;
string cl(string s)
{
for (int i = 'A'; i <= 'Z'; i++) v[i] = v1[i];
if (s[0] != '(') return "0";
int len = s.size();
ll ans = 0;
while (!sta.empty()) sta.pop();
for (int i = 0; i < len; i++)
{
if (s[i] == '(')
{
sta.push(s[i]);
}else
if (s[i] == ')')
{
char b = sta.top();
sta.pop();
char a = sta.top();
sta.pop();
sta.pop();//'('删掉
ll x = v[a].first, y = v[a].second,z = v[b].second;
if (y != v[b].first) return "error";
ans += x*y*z;
v[a].first = x, v[a].second = z;
sta.push(a);
}
else
{
sta.push(s[i]);
}
}
string temp = "";
while (ans)
{
temp = char(ans % 10 +'0')+ temp;
ans /= 10;
}
return temp;
}
int main()
{
//freopen("F:\rush.txt", "r", stdin);
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%s", s);
int x, y;
scanf("%d%d", &x, &y);
v[s[0]] = { x,y };
}
for (int i = 'A'; i <= 'Z'; i++) v1[i] = v[i];
string s;
while (cin >> s) cout << cl(s) << endl;
return 0;
}