nyoj 题目467 中缀式变后缀式

来源:互联网 发布:淘宝第二次申请售后 编辑:程序博客网 时间:2024/05/16 10:31

                                                                       中缀式变后缀式

时间限制:1000 ms  |            内存限制:65535 KB
难度:3
描述
人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
输入
第一行输入一个整数n,共有n组测试数据(n<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式的中缀式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
数据保证除数不会为0
输出
每组都输出该组中缀式相应的后缀式,要求相邻的操作数操作符用空格隔开。
样例输入
21.000+2/4=((1+2)*5+1)/4=
样例输出
1.000 2 4 / + =1 2 + 5 * 1 + 4 / =
来源
数据结构
上传者
mix_math

解法:栈模拟!

#include<bits/stdc++.h>using namespace std;string s,str;int yxj(char ch){    switch(ch)    {        case '+':        case '-':return 1;        case '*':        case '/':return 2;        default: return 0;    }}int main(){    int T;    cin>>T;    while(T--)    {        cin>>s;        stack<char>pq;        pq.push('#');        int len=s.size(),i=0;        str.clear();        while(i<len-1)        {            if(s[i]=='(')            {                pq.push(s[i]);                i++;            }            else if(s[i]==')')            {                while(pq.top()!='(')                {                    str+=pq.top();                    pq.pop();                    str+=' ';                }                pq.pop();                i++;            }            else if(s[i]=='+'||s[i]=='-'||s[i]=='*'|s[i]=='/')            {                while(yxj(pq.top())>=yxj(s[i]))                {                    str+=pq.top();                    str+=' ';                    pq.pop();                }                pq.push(s[i]);                i++;            }            else            {                while(s[i]>='0'&&s[i]<='9'||s[i]=='.')                {                    str+=s[i];                    i++;                }                str+=' ';            }        }        while(pq.top()!='#')        {            str+=pq.top();            pq.pop();            str+=' ';        }        str+='=';        cout<<str<<"\n";    }    return 0;}


 

0 0
原创粉丝点击