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).
- 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了,哈哈!