NYOJ 257 中缀表达式表示成后缀表达式
2012-03-24 11:11 javaspring 阅读(225) 评论(0) 编辑 收藏 举报话说这道题代码那个丑陋啊,,写出来我自己都不想再看第二遍啊。。。看了看聪神的代码,还消耗我3个NYOJ币啊,,更扯得是,聪神的代码我看不懂啊,,,,卧槽。。。这道题不再多说了,数据结构上有详细的介绍,主要就是输入的时候巧妙利用sscanf()函数就可以了。。题目:
郁闷的C小加(一)
时间限制:1000 ms | 内存限制:65535 KB
难度:3
- 描述
-
我们熟悉的表达式如a+b、a+b*(c+d)等都属于中缀表达式。中缀表达式就是(对于双目运算符来说)操作符在两个操作数中间:num1 operand num2。同理,后缀表达式就是操作符在两个操作数之后:num1 num2 operand。ACM队的“C小加”正在郁闷怎样把一个中缀表达式转换为后缀表达式,现在请你设计一个程序,帮助C小加把中缀表达式转换成后缀表达式。为简化问题,操作数均为个位数,操作符只有+-*/ 和小括号。
- 输入
- 第一行输入T,表示有T组测试数据(T<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个表达式。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。并且输入数据不会出现不匹配现象。
- 输出
- 每组输出都单独成行,输出转换的后缀表达式。
- 样例输入
-
21+2(1+2)*3+4*5
- 样例输出
-
12+12+3*45*+
#include <iostream> #include <cstdio> #include <string.h> #include <string> #include <stack> using namespace std; struct oper{ char op; int level; }p; int fun(char cc){ if(cc=='+'||cc=='-') return 1; else if(cc=='*'||cc=='/') return 2; else if(cc=='(') return 3; else if(cc==')') return 0; } int main(){ int numcase; scanf("%d",&numcase); while(numcase--){ string str; cin>>str; int len=str.size(),pos=0,ll=0,num=0; char ch; stack<oper> ss; p.op=' ';p.level=0;ss.push(p); while(pos<len){ if(str[pos]<='9'&&str[pos]>='0'){ sscanf(&str[pos],"%d%n",&num,&ll); printf("%d",num); pos+=ll; } else{ sscanf(&str[pos],"%c%n",&ch,&ll); pos+=ll;p.op=ch;p.level=fun(ch); if(p.op==')'){ while(ss.top().op!='('){ printf("%c",ss.top().op); ss.pop(); } ss.pop(); } else if(p.level>ss.top().level||ss.top().op=='(') ss.push(p); else{ while(p.level<=ss.top().level&&ss.top().op!='('){ printf("%c",ss.top().op); ss.pop(); } ss.push(p); } } } while(!ss.empty()){ printf("%c",ss.top().op); ss.pop(); } printf("\n"); } return 0; }