Pagini recente » Cod sursa (job #2164111) | Cod sursa (job #1055493) | Cod sursa (job #457105) | Cod sursa (job #570123) | Cod sursa (job #1819388)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long long int lli;
typedef pair < int, int> dbl;
const int maxInt = 1e9*2;
const lli maxLong = 1e18*2;
bool operand(char ch){
if(ch >= '0' && ch <= '9')
return(1);
return(0);
}
bool operator0(char ch){
if(ch == '+' || ch == '/' || ch == '*' || ch == '-')
return(1);
return(0);
}
bool lessOp(char op, char op2){
int st, dr;
if(op == '+' || op == '-')
st = 1;
if(op == '*' || op == '/')
st = 2;
if(op2 == '+' || op2 == '-')
dr = 1;
if(op2 == '*' || op2 == '/')
dr = 2;
return(st <= dr);
}
int toInt(string cnt){
istringstream ss(cnt);
int val;
ss >> val;
return(val);
}
int toOp(char ch){
if(ch == '+')
return(-1);
if(ch == '-')
return(-2);
if(ch == '*')
return(-3);
if(ch == '/')
return(-4);
}
int main(){
//ifstream cin("input.in");
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
ios::sync_with_stdio(0);
string str;
//string ans;
vector <int> ans;
stack <char> stk;
cin >> str;
for(int i = 0; (unsigned)i < str.size(); i++){
if(operand(str[i])){
string cnt;
while(operand(str[i])){
cnt+=str[i];
i++;
}
i--;
//ans+=str[i];
ans.push_back(toInt(cnt));
}
else
if(operator0(str[i])){
while(!stk.empty() && stk.top() != '(' && lessOp(str[i], stk.top())){
//ans+=stk.top();
ans.push_back(toOp(stk.top()));
stk.pop();
}
stk.push(str[i]);
}
else if(str[i] == '(')
stk.push(str[i]);
else if(str[i] == ')'){
while(!stk.empty() && stk.top() != '('){
ans.push_back(toOp(stk.top()));
stk.pop();
}
stk.pop();
}
}
while(!stk.empty()){
ans.push_back(toOp(stk.top()));
stk.pop();
}
stack <int> count;
for(int i = 0; (unsigned)i < ans.size(); i++){
if(ans[i] >= 0)
count.push(ans[i]);
else if(ans[i] < 0){
int a, b, c;
a = count.top();
count.pop();
b = count.top();
count.pop();
if(ans[i] == -1)
c = a + b;
else
if(ans[i] == -2)
c = abs(a - b);
else
if(ans[i] == -3)
c = a * b;
else
if(ans[i] == -4)
c = b / a;
count.push(c);
}
}
for(int i = 0; i < ans.size(); i++){
if(ans[i] == -1)
cout << '+' << ' ' ;
else
if(ans[i] == -2)
cout << '-' << ' ';
else
if(ans[i] == -3)
cout << '*' << ' ';
else
if(ans[i] == -4)
cout << '/' << ' ';
else cout << ans[i] << ' ';
}
cout << endl;
//cout << ans;
cout << count.top();
return(0);
}