Infix variable suffix type time limit: 1000 MS | memory limit: 65535 kb difficulty: 3
-
Description
-
People's Daily habit is to write an arithmetic expression as an infix, but it is more "used" for machines, general Data Structure books have relevant content for reference. I will not go into details here. Now your task is to change the infix into a suffix.
-
Input
-
Enter an integer N in the first line. There are N groups of test data (n <10 ).
Each group of test data has only one row. It is a string of no more than 1000 characters, indicating the infix of this formula. Each formula ends with "=. This expression only contains the +-*/and parentheses. Parentheses can be nested. Data ensures that no negative numbers are displayed in the input operations.
Data guarantee that the divisor is not 0
-
Output
-
Each group outputs the suffix corresponding to the infix in this group. Adjacent operand operators are required to be separated by spaces.
-
Sample Input
-
21.000+2/4=((1+2)*5+1)/4=
-
Sample output
-
1.000 2 4 / + =1 2 + 5 * 1 + 4 / =
-
Source
-
Data Structure
-
Uploaded
-
Mix_math :... question: Two stacks are required. One is the symbol sta stack and the other is the suffix out stack. Each time a character is read in the Buf, if it is a number or '. ', it is directly stored in the out stack. If it is another character, it is placed in the sta stack, on the premise that the priority in the sta stack is strictly reduced.
# Include <stdio. h> # include <string. h> # include <ctype. h ># define maxn 1010 char Buf [maxn], out [maxn <1]; char sta [maxn]; // symbol stack int ID, Id2; int getlevel (char ch) {Switch (CH) {Case '(': Return 0; Case '+': Case '-': return 1; Case '*': case '/': return 2 ;}} void check (char ch) {int level; if (CH = '(') sta [Id2 ++] = CH; else if (CH = ') {While (STA [id2-1]! = '(') {Out [ID ++] = sta [-- Id2]; out [ID ++] = '';}-- Id2 ;} else {While (Id2 & getlevel (STA [id2-1])> = getlevel (CH) {out [ID ++] = sta [-- Id2]; out [ID ++] = '';} sta [Id2 ++] = CH ;}} void solve () {int I, sign; id = Id2 = 0; for (I = Sign = 0; Buf [I]! = '; ++ I) {If (isdigit (BUF [I]) | Buf [I] = '. ') {out [ID ++] = Buf [I]; Sign = 1 ;}else {If (sign) {out [ID ++] = ''; sign = 0 ;}check (BUF [I]) ;}while (Id2) {If (sign) {out [ID ++] = ''; Sign = 0 ;} out [ID ++] = sta [-- Id2]; out [ID ++] = '';} out [ID] = '\ 0 '; printf ("% s = \ n", out);} int main () {// freopen ("stdin.txt", "r", stdin); int T; scanf ("% d", & T); While (t --) {scanf ("% s", Buf); solve () ;}return 0 ;}
Nyoj467 [Stack]