Pagini recente » Monitorul de evaluare | Cod sursa (job #1501878) | Cod sursa (job #1723617) | Cod sursa (job #1544450) | Cod sursa (job #1723612)
#include <fstream>
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
std::string s;
std::stack<std::pair<char,int> >S1;
std::stack<int>S2;
const int Nmax = 100005;
int priority(char c){
if(c == '+' || c == '-')
return 1;
if(c == '*' || c == '/')
return 2;
return 3;
}
void eliminate(int k){
while(S1.top().first != '(' && s[k] == ')' || S1.top().second >= priority(s[k]) ){
char op = S1.top().first; S1.pop();
int x = S2.top(); S2.pop();
int y = S2.top(); S2.pop();
if(op == '-')
S2.push(y - x);
if(op == '+')
S2.push(y + x);
if(op == '*')
S2.push(y * x);
if(op == '/')
S2.push(y / x);
}
}
int dijkstraTwoStack( void ){
for(int pz = 0; pz < s.length(); ++ pz){
if(s[pz] == ')'){
eliminate(pz);
S1.pop();
continue;
}
if(s[pz] == '('){
S1.push(std::make_pair('(',-1));
continue;
}
if('0' <= s[pz] && s[pz] <= '9'){
int aux = 0;
while('0' <= s[pz] && s[pz] <= '9'){
aux = aux * 10 + s[pz] - 48;
++pz;
}
--pz;
S2.push(aux);
continue;
}
eliminate(pz);
S1.push(std::make_pair(s[pz],priority(s[pz])));
}
return S2.top();
}
int main()
{
std::ifstream streamIn("evaluare.in");
std::ofstream streamOut("evaluare.out");
streamIn.sync_with_stdio(false);
streamIn >> s;
s = "(" + s + ")";
streamOut << dijkstraTwoStack();
return 0;
}