http://pastebin.com/1CCUfPp3
-
// Victor Padilla (vector9x@gmail.com) - SPOJ ONP
-
import java.io.*;
-
import java.util.*;
-
-
public class TransformExp {
-
static void dbg(Object...os) {
-
System.err.println(Arrays.deepToString(os));
-
}
-
static BufferedReader input;
-
static StringTokenizer _stk;
-
static String readln() throws IOException {
-
String l = input.readLine();
-
if(l!=null) _stk = new StringTokenizer(l," ");
-
return l;
-
}
-
static String next() { return _stk.nextToken(); };
-
static int nextInt() { return Integer.parseInt(next()); }
-
public static void main(String[] args) throws IOException {
-
Locale.setDefault(Locale.US);
-
input = new BufferedReader(new InputStreamReader(System.in));
-
-
readln();
-
int numcases = nextInt();
-
for(int caseid=1; caseid<=numcases; caseid++) {
-
String exp = readln();
-
for(char c : separadores)
-
exp = exp.replace(""+c, " "+c+" ");
-
-
tknzr = new StringTokenizer(exp, " ");
-
Node raiz = parser();
-
-
salida = new StringBuilder();
-
raiz.postOrder();
-
System.out.println(salida);
-
}
-
}
-
-
static StringTokenizer tknzr;
-
static final char[] separadores={'(',')','+','-','*','/','^'};
-
-
static StringBuilder salida;
-
-
static Node parser() {
-
Node res = new Node();
-
String tk = tknzr.nextToken();
-
if(tk.equals("(")) { //caso recursivo, una subexpresion
-
res.izq = parser(); //leo el primer operando, que es una expresion
-
res.dato = tknzr.nextToken(); //leo el operador, +, -, ...
-
res.der = parser(); //leo el segundo operando
-
tknzr.nextToken(); //leo (y boto) el parentesis de cerrar
-
}
-
else { //caso trivial, una variable
-
res.dato = tk;
-
}
-
-
return res;
-
}
-
-
static class Node {
-
String dato;
-
Node izq, der;
-
-
void postOrder() {
-
if(izq!=null) { //se espera que tambien der!=null
-
izq.postOrder();
-
der.postOrder();
-
}
-
salida.append(dato);
-
}
-
}
-
}