您的位置:首页 > 其它

nyoj 1272 表达式求值

2017-04-17 08:55 381 查看

表达式求值



表达式求值基础:表达式求值基础题

ps:对Smax预处理一下,转换成普通的表达式就行了

代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stack>
#include<algorithm>
using namespace std;

#define max(a,b) (a>b?a:b)
stack<char>s1,s2;
stack<int>s3;
char str[1010],ch[1010];
int len;

void pretreatment(int n)//预处理
{
len=0;
for(int i=0; i<n; ++i)
{
if(str[i]=='S')
{
i+=5;
ch[len++]='(';
while(str[i]!=',')

4000
ch[len++]=str[i++];
ch[len++]=')';
ch[len++]='S';
ch[len++]='(';
i++;
while(str[i]!=')')
ch[len++]=str[i++];
ch[len++]=')';
}
else
ch[len++]=str[i];
}
ch[len]='\0';
}

int priority(char c)//优先级比较
{
if(c=='(')
return 5;
if(c=='S')
return 4;
if(c=='*')
return 3;
if(c=='+')
return 2;
if(c==')')
return 1;
}

int Scal(int a,int b,char op)//进行运算
{
if(op=='+')
return a+b;
if(op=='*')
return a*b;
if(op=='S')
{
int x=0,y=0;
while(a)
{
x+=a%10;
a/=10;
}
while(b)
{
y+=b%10;
b/=10;
}
return max(x,y);
}
}

void Transform()//转化为后缀表达式
{
for(int i=0; i<len; ++i)
{
if(ch[i]>='0'&&ch[i]<='9')
{
if(i+1<len&&(ch[i+1]<'0'||ch[i+1]>'9')||i==len-1)
{
s2.push(ch[i]);
s2.push('#');
}
else
s2.push(ch[i]);
}
else
{
if(s1.empty()||ch[i]=='('||priority(ch[i])>priority(s1.top()))
s1.push(ch[i]);
else if(ch[i]==')')
{
while(s1.top()!='(')
{
s2.push(s1.top());
s1.pop();
}
s1.pop();
}
else
{
while(!s1.empty()&&priority(ch[i])<=priority(s1.top())&&s1.top()!='(')
{
s2.push(s1.top());
s1.pop();
}
s1.push(ch[i]);
}
}
}
int k=0;
while(!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
while(!s1.empty())
{
ch[k++]=s1.top();
s1.pop();
}
ch[k]='\0';
}

int Cal(int n)
{
int x,y;
for(int i=0; i<n; ++i)
{
if(ch[i]=='#')
continue;
else if(ch[i]=='+'||ch[i]=='*'||ch[i]=='S')
{
x=s3.top();
s3.pop();
y=s3.top();
s3.pop();
x=Scal(y,x,ch[i]);
s3.push(x);
}
else
{
int result=0;
while(ch[i]>='0'&&ch[i]<='9')
{
result=result*10+ch[i]-'0';
i++;
}
s3.push(result);
}
}
return s3.top();
}

int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",str);
pretreatment(strlen(str));
Transform();
printf("%d\n",Cal(strlen(ch)));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: