内存限制:128 MB时间限制:1.000 S
评测方式:文本比较
题目描述
输入一个中缀表达式(由 0-9 组成的运算数、加+减—乘*除/四种运算符、左右小括号组成。注意“—”也可作为负数的标志,表达式以“@”作为结束符),判断表达式是否合法,如果不合法,请输出“NO”;否则请把表达式转换成后缀形式,再求出后缀表达式的值并输出。
注意:必须用栈操作,不能直接输出表达式的值。
输入
第一行为一个以 @ 结束的字符串。
输出
如果表达式不合法,请输出“NO”,要求大写。
如果表达式合法,请输出计算结果。
样例输入
1+2*8-9
样例输出
8
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char a[1000];
int s1[1000];
char s2[1000];
int r[200];
int top1,top2;
int flag;
void out(char c)
{
if(c=='+')s1[--top1]+=s1[top1+1];
else if(c=='-')s1[--top1]-=s1[top1+1];
else if(c=='*')s1[--top1]*=s1[top1+1];
else if(c=='/')s1[--top1]/=s1[top1+1];
}
int main()
{
int m=0,n=0;
r['+']=1;
r['-']=1;
r['*']=2;
r['/']=2;
scanf("%s",a);
if(r[a[0]])flag=1;
int i=0;
while(a[i]!='\0')
{
if(a[i]>='0'&&a[i]<='9')
{
int x=0;
while(a[i]>='0'&&a[i]<='9')
{
x=x*10+a[i]-'0';
i++;
}
s1[++top1]=x;
}
if(a[i]=='(')
{
s2[++top2]='(';
m++;
}
if(a[i]==')')
{
n++;
while(s2[top2]!='(')
{
out(s2[top2]);
top2--;
}
top2--;
}
if(r[a[i]]&&r[a[i+1]])flag=1;
if(r[a[i]])
{
while(r[a[i]]<=r[s2[top2]])
{
out(s2[top2]);
top2--;
}
top2++;
s2[top2]=a[i];
}
i++;
if(flag==1)
{
cout<<"NO";
return 0;
}
}
while(top2!=0)
{
out(s2[top2]);
top2--;
}
if(m!=n)
{
cout<<"NO";
return 0;
}
cout<<s1[top1];
return 0;
}