Pagini recente » Cod sursa (job #1719486) | Cod sursa (job #2019081) | Cod sursa (job #32566) | Cod sursa (job #541484) | Cod sursa (job #1818949)
#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){
if((op == '+' || op == '-') && (op2 == '/' || op2 == '*'))
return(1);
return(0);
}
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("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() && 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.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 = 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 << ans;
cout << count.top();
return(0);
}