原本打算用栈将中缀表达式转后缀表达式,然后用栈对后缀表达式求值,但需要两个栈代码及其复杂以及本人这类型代码写的太少,自己一个人写不出来,就参考了网上的思路,用双指针法得结果,由于我是在HD提交,unordered_map居然被禁止使用,导致一直编译错误,最后用map才过
#include<iostream>
#include<algorithm>
#include<unordered_map>//改成#include<map> hd就可以过
#include<cstring>
using namespace std;
int a[1001],cnt;
int main()
{
int number;
string mo,ch;
undered_map<string,int>mapp;//map<string,int>mapp
while(cin>>mo&&mo!="END_OF_FIRST_PART")
{
cin>>number;
mapp.insert({mo,number});
}
while(cin>>ch&&ch!="0")
{
memset(a,0,sizeof(a));
cnt = 0;
bool flag = true;
for(int i=0;i<ch.size();i++)
{
string t;
if(ch[i]>='A'&&ch[i]<='Z')
{
int j = i,number = 0;
t += ch[i];
while(j+1<ch.size()&&ch[j+1]>='a'&&ch[j+1]<='z')
{
j++;
t += ch[j];
}
if(mapp.find(t)==mapp.end())
{
cout<<"UNKNOWN"<<endl;
flag = false;
break;
}
if(j+1<ch.size()&&ch[j+1]>='0'&&ch[j+1]<='9')
{
while(j+1<ch.size()&&ch[j+1]>='0'&&ch[j+1]<='9')
{
j++;
number = number*10 + ch[j]-'0';
}
}
else number = 1;
a[++cnt] = number*mapp[t];
i = j;
}
else if(ch[i]=='(') a[++cnt] = -1;
else if(ch[i]==')')
{
int number = 0, sum = 0,j = i;
while(j+1<ch.size()&&ch[j+1]>='0'&&ch[j+1]<='9')
{
j++;
number = number*10 + ch[j]-'0';
}
while(a[cnt]!=-1)
{
sum += a[cnt--];
}
a[cnt] = sum*number;
i = j;
}
}
if(flag)
{
int sum = 0;
for(int i=1;i<=cnt;i++) sum += a[i];
cout<<sum<<endl;
}
}
}