Transform the algebraic expression with brackets into RPN form (Reverse Polish Notation). Two-argument operators: +, -, *, /, ^ (priority from the lowest to the highest), brackets ( ). Operands: only letters: a,b,...,z. Assume that there is only one RPN form (no expressions like a*b*c).
Input
t [the number of expressions <= 100]
expression [length <= 400]
[other expressions]
Text grouped in [ ] does not appear in the input file.
Output
The expressions in RPN form, one per line.
Example
Input:
3
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))
Output:
abc*+
ab+zx+*
at+bac++cd+^*
实际就是中缀表达式变后缀
- line=gets.to_i
- priority={'+'=>1,'-'=>1,'*'=>2,'/'=>2,'^'=>3,'('=>4}
- results=[]
- for i in 1..line
- operator=[]
- result=[]
- exp=gets.chomp
- 0.step(exp.length-1,1) { |x|
- if exp[x]==')'
- while operator.last!='('
- result.push(operator.pop)
- end
- operator.pop
- next
- end
- if priority.has_key? exp[x]
- if operator.empty?
- operator.push(exp[x])
- elsif priority[operator.last]>=priority[exp[x]] && operator.last!='('
- #错误的地方,注意
- result.push(operator.pop)
- operator.push(exp[x])
- else
- operator.push(exp[x])
- end
- else
- result.push(exp[x])
- end
- }
- results<<result.join
- end
- results.each do |x|
- puts x
- end
注:以上代码是有错误的,比如这样的输入(a+b*c^d+e),但是spoj居然还是判AC了,哈哈!
转载于:https://blog.51cto.com/lockrock/908796