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+^*
 
实际就是中缀表达式变后缀
 
 
  
  1. line=gets.to_i  
  2. priority={'+'=>1,'-'=>1,'*'=>2,'/'=>2,'^'=>3,'('=>4}  
  3. results=[]  
  4. for i in 1..line  
  5.     operator=[]  
  6.     result=[]  
  7.     exp=gets.chomp  
  8.     0.step(exp.length-1,1) { |x|  
  9.         if exp[x]==')' 
  10.             while operator.last!='(' 
  11.                 result.push(operator.pop)  
  12.             end 
  13.             operator.pop  
  14.             next 
  15.         end 
  16.         if priority.has_key? exp[x]  
  17.             if operator.empty?  
  18.                 operator.push(exp[x])  
  19.             elsif priority[operator.last]>=priority[exp[x]] && operator.last!='(' 
  20.                 #错误的地方,注意
  21.  result.push(operator.pop)  
  22.                 operator.push(exp[x])  
  23.             else 
  24.                 operator.push(exp[x])  
  25.             end 
  26.         else 
  27.             result.push(exp[x])  
  28.         end 
  29.     }  
  30.     results<<result.join  
  31. end 
  32.  
  33. results.each do |x|  
  34.     puts x  
  35. end 


 

注:以上代码是有错误的,比如这样的输入(a+b*c^d+e),但是spoj居然还是判AC了,哈哈!