后缀表达式

来源:互联网 发布:查找excel两表相同数据 编辑:程序博客网 时间:2024/05/21 11:58

开两个栈,一个存符号,另一个存数字;

存符号的栈保证优先级递增(相等也不行);
否则,10-3+7,答案会是0,(7+3-10);

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>using namespace std;typedef long long ll;const ll MAXN=210;ll stack[MAXN],a[MAXN];char stack_f[MAXN],s[MAXN],b[MAXN];ll len,top,top_f,x,y,tot;ll get(char c)//得到优先级;{    switch(c)    {        case '(': return 0;        case '+': return 1;        case '-': return 1;        case '*': return 2;        case '/': return 2;        case '^': return 2147483647;    }}ll ji(ll x,ll y,char c){    switch(c)//计算;    {        case '+': return x+y;        case '-': return x-y;        case '*': return x*y;        case '/': return x/y;         case '^': return pow(x,y);    }}void done(){    while(stack_f[top_f]!='(')    {        x=stack[top],--top;        y=stack[top],--top;        tot=ji(y,x,stack_f[top_f]);        top_f--;        stack[++top]=tot;    }    if(stack_f[top_f]=='(') top_f--;    return;}void calc(char c){    if(c==')')    {        done();        return;    }    else if(c=='('  || !top_f || get(stack_f[top_f])<get(c))    {         stack_f[++top_f]=c;        return;    }    else if(get(stack_f[top_f])>=get(c))    {//如果优先级无法递增,那么将前面的计算完,直到为空或者栈顶符号优先级小于当前符号;        while(get(stack_f[top_f])>=get(c) && top_f)        {            x=stack[top],top--;            y=stack[top],top--;            tot=ji(y,x,stack_f[top_f]);            top_f--;            stack[++top]=tot;        }        stack_f[++top_f]=c;    }    return;}void solve(){    scanf("%s",s+1);    len=strlen(s+1);    for(ll i=1;i<=len;)    {        ll f=1;        if((s[i]=='-' && s[i-1]=='\0') || (s[i]=='-' && s[i-1]=='(')) f=-1,i++;//特判负数;        if(s[i]>='0' && s[i]<='9')        {            ll num=0;            while(s[i]>='0' && s[i]<='9')                num=num*10+s[i]-'0',i++;            stack[++top]=num*f;        }        else calc(s[i]),i++;    }    while(stack_f[top_f]=='(') top_f--;    while(top>=2)    {        x=stack[top],top--;        y=stack[top],top--;        tot=ji(y,x,stack_f[top_f]);        top_f--;        stack[++top]=tot;    }    cout<<stack[top]<<'\n';    return;}int main(){    solve();    return 0;}
原创粉丝点击