#include #include #include #include #include int pri(char c) { if (c=='+' || c=='-') return 1; else if(c=='*' || c=='/') return 2; else return 0; } int main() { int n; cin >> n; char buf[300]; gets(buf); for (int ca=1; ca<=n; ca++) { gets(buf); stack v; list l; for (char* c=buf; *c; c++) { switch (*c) { case '(': v.push(*c); break; case ')': while (v.top() != '(') { l.push_back(v.top()); v.pop(); } v.pop(); break; case '+': case '-': case '*': case '/': while (!v.empty() && pri(v.top()) && pri(v.top()) >= pri(*c)) { l.push_back(v.top()); v.pop(); } v.push(*c); break; default: l.push_back(*c); break; } } while (!v.empty()) { l.push_back(v.top()); v.pop(); } /* for (list::iterator i=l.begin(); i!=l.end(); i++) cout << *i; */ /////////////////////////////////////////////////// stack vs; stack vc; string tmp; for (list::iterator i=l.begin(); i!=l.end(); i++) { switch (*i) { case '+': tmp = vs.top(); vs.pop(); tmp = vs.top() + "+" + tmp; vs.pop(); vc.pop(); vc.pop(); vc.push('+'); vs.push(tmp); break; case '-': if(pri(vc.top())==1) { tmp = vs.top(); vs.pop(); tmp = vs.top() + "-(" + tmp + ")"; vs.pop(); vc.pop(); vc.pop(); vs.push(tmp); vc.push('-'); } else { tmp = vs.top(); vs.pop(); tmp = vs.top() + "-" + tmp; vs.pop(); vc.pop(); vc.pop(); vs.push(tmp); vc.push('-'); } break; case '*': if (pri(vc.top())==1) tmp = "(" + vs.top() + ")"; else tmp = vs.top(); vs.pop(); vc.pop(); if (pri(vc.top())==1) tmp = "(" + vs.top() + ")" + "*" + tmp; else tmp = vs.top() + "*" + tmp; vs.pop(); vc.pop(); vs.push(tmp); vc.push('*'); break; case '/': if (pri(vc.top())!=0) tmp = "(" + vs.top() + ")"; else tmp = vs.top(); vs.pop(); vc.pop(); if (pri(vc.top())==1) tmp = "(" + vs.top() + ")" + "/" + tmp; else tmp = vs.top() + "/" + tmp; vs.pop(); vc.pop(); vs.push(tmp); vc.push('/'); break; default: vs.push(string(1, *i)); vc.push('x'); break; } } if (vs.empty()) cout << endl; else cout << vs.top() << endl; } return 0; }