-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10.cpp
96 lines (89 loc) · 1.76 KB
/
10.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
using namespace std;
stack<char>post;
stack<string>solution;
string input;
bool isoperator(char s){
switch(s){
case '+':case '-':case '*':case '/':return true;
case '(':case ')':case'=': return true;
default:return false;
};
}
int isp(char s){
if(s=='+'||s=='-') return 2;
else if(s=='*'||s=='/') return 3;
else if(s=='(') return 0;
else if(s=='=') return 0;
}
int icp(char s){
if(s=='+'||s=='-') return 2;
else if(s=='*'||s=='/') return 3;
else if(s=='(') return 7;
else if(s=='=') return 0;
else if(s==')') return 1;
}
int main(){
fstream fin("input1");
//fin>>input;
string el;
while(getline(fin,input)){
//s.clear();
stringstream s(input);
//s<<input;
stringstream postfix;
while(getline(s,el,' ')){
char e=el[0];
if(!isoperator(e)){
postfix<<el<<" ";
}
else if(post.empty()||isp(post.top())<icp(e)){
post.push(e);
}
else{
while(!post.empty()&&isp(post.top())>=icp(e)){
postfix<<post.top()<<" ";
post.pop();
}
if(e==')'){
post.pop();
}
else
post.push(e);
}
}
while(!post.empty()){
postfix<<post.top()<<" ";
post.pop();
}
string posfixexp(postfix.str());
// cout<<posfixexp<<endl;
string result, pstring;
int i=0;
while(getline(postfix,pstring,' ')){
result="";
char el=pstring[0];
if(!isoperator(el)){
solution.push(pstring);
}
else{
string first=solution.top();
solution.pop();
string second=solution.top();
solution.pop();
if(el=='='){
result=second+" "+el+" "+first;
}
else{
result="t"+to_string(i++);
cout<<result+" = "+second+" "+el+" "+first<<endl;
}
solution.push(result);
}
}
cout<<result<<endl;
}
}