zoukankan      html  css  js  c++  java
  • SPOJ #4 Transform the Expression

    Not hard to know it is simply transform from in-order to post-order.
    My first idea is to build a tree from in-order string and then traverse the tree by post-order - naive so slow.
    Subtle stack manipulation solves it - stack only for operators:
    http://cs.nyu.edu/courses/Fall12/CSCI-GA.1133-002/notes/InfixToPostfixExamples.pdf

    BTW, I love Ruby more.

     1 # SPOJ #4 QNR
     2 
     3 cnt = gets
     4 cnt = cnt.to_i
     5 
     6 #
     7 def process(str)    
     8     stk = []
     9     i = 0
    10     while i < str.length do
    11         c = str[i]
    12         case c
    13         when 'a'..'z'
    14             print c        
    15         when '+', '-'
    16             stk.push(c)        
    17         when '*', '/'
    18             while !stk.empty? && (stk.last != '+' or stk.last != '-') do
    19                 if(stk.last == '(')
    20                     break
    21                 end
    22                 print stk.pop()
    23             end
    24             stk.push(c)        
    25         when '^'
    26             while !stk.empty? && stk.last == '^' do
    27                 if(stk.last == '(')
    28                     break
    29                 end
    30                 print stk.pop()
    31             end
    32             stk.push(c)
    33         when '('
    34             stk.push(c)
    35         when ')'                
    36             while !stk.empty? && stk.last != '(' do
    37                 if(stk.last == '(')
    38                     break
    39                 end
    40                 print stk.pop()
    41             end
    42             if(stk.last == '(')
    43                 stk.pop()
    44             end
    45         end
    46         i += 1
    47     end    
    48     while !stk.empty? do
    49         print stk.pop()
    50     end
    51     puts
    52 end # def process
    53 
    54 i = 0
    55 while i < cnt do    
    56     str = gets.to_s.downcase
    57     process(str)
    58     i += 1
    59 end
    View Code
  • 相关阅读:
    Linux踩坑填坑记录
    Scala安装后,在IDEA中配置
    Centos 搭建Hadoop
    conductor FAQ
    conductor Workflow Metrics
    conductor APIs
    Extending Conductor
    conductor任务域
    Conductor Task Workers
    Conductor Server
  • 原文地址:https://www.cnblogs.com/tonix/p/3537867.html
Copyright © 2011-2022 走看看