SPOJ Classical problems 4 TRANSFORM THE EXPRESSION(ONP)

http://www.spoj.pl/problems/ONP/

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+^*

中缀表达式转后缀表达式,使用栈即可。

这里用stl库,不过自己手写效率要高一些。

================================================

如为字母则放入结果

如为运算符,则将其与栈顶优先级比较,如低于栈顶则进栈,否则放入结果

左括号直接进栈,右括号退栈至最近的左括号

=================================================

 1 #include <iostream>
 2 #include <stack>
 3 #include <cctype>
 4 #include <vector>
 5 #include <cstdio>
 6 #include <string>
 7 
 8 using namespace std;
 9 
10 char p[1000];
11 
12 int main()
13 {
14     freopen("in.txt", "r", stdin);
15 
16 
17 
18     p['+'] = '1';
19     p['-'] = '2';
20     p['*'] = '3';
21     p['/'] = '4';
22     p['^'] = '5';
23 
24 
25     int n;
26     cin >> n;
27     while (n--)
28     {
29         stack<char> st;
30         vector<char> cvec;
31         char c;
32         char priority = 6;
33         string str;
34         cin >> str;
35 
36         for (int i=0; i<str.size(); ++i)
37         {
38             c = str[i];
39             if (isalpha(c))
40             {
41                 cvec.push_back(c);
42             }
43 
44             if (c == '(')
45             {
46                 st.push(c);
47                 priority = '6';
48             }
49             if (c=='+' || c=='-' || c=='*' || c=='/' || c=='^')
50             {
51                 if (p[c] >= priority)
52                 {
53                     cvec.push_back(c);
54                 }
55                 else
56                 {
57                     st.push(c);
58                     priority = p[c];
59                 }
60             }
61             if (c == ')')
62             {
63                 char retr = st.top();
64                 st.pop();
65 
66                 while (retr != '(')
67                 {
68                     cvec.push_back(retr);
69                     retr = st.top();
70                     st.pop();
71                 }
72                 priority = '6';
73             }
74 
75         }
76         for (vector<char>::iterator iter=cvec.begin(); iter!=cvec.end(); ++iter)
77         {
78             cout << *iter;
79         }
80         cout << endl;
81     }
82     return 0;
83 }
posted @ 2012-06-03 15:30  漂木  阅读(302)  评论(0编辑  收藏  举报