Pagini recente » Cod sursa (job #251290) | Cod sursa (job #2800364) | Cod sursa (job #1679620) | Cod sursa (job #1556245) | Cod sursa (job #2063566)
#include <fstream>
#include<stack>
#include<queue>
#include<string.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char s[100003];
stack<char> ST;
stack<int> STN;
queue<string> FP;
string aux;
int prioritate(char o)
{
switch (o) {
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
case '(': return 0;
}
}
///adaug un char in coada de stringuri
void Tudor(char c)
{
aux.clear();
aux.push_back(c);
FP.push(aux);
}
void operatie(char o)
{
int x=STN.top(); STN.pop();
int y=STN.top(); STN.pop();
switch (o) {
case '+': STN.push(x+y); break;
case '-': STN.push(y-x); break;
case '*': STN.push(x*y); break;
case '/': STN.push(y/x); break;
}
}
int main()
{
int n;
int nr;
int i;
f>>s;
///transform parantezele
for(i=0;s[i];++i)
if(s[i]=='[') s[i]='(';
else if(s[i]==']') s[i]=')';
else if(s[i]=='{') s[i]='(';
else if(s[i]=='}') s[i]=')';
///adaug prima paranteza deschisa in stiva de op
ST.push('(');
for(i=0;s[i];++i)
if(s[i]=='(') ST.push('(');
else
if(s[i]>='0' && s[i]<='9') ///am ajuns la un nr
{
aux.clear();
while(s[i]>='0' && s[i]<='9'){
aux.push_back(s[i]);
++i;
}
FP.push(aux);
i--;
}
else
if(s[i]==')')
{
while(ST.top()!='('){
Tudor(ST.top());
ST.pop();
}
ST.pop();
}
else {
while(prioritate(ST.top())>=prioritate(s[i]))
{
Tudor(ST.top());
ST.pop();
}
ST.push(s[i]);
}
///am ajuns la sf => extrag tot din stiva si pun in FP
while(ST.top()!='(') {Tudor(ST.top());
ST.pop();}
///evaluarea expresiei
while(!FP.empty())
{
aux=FP.front();
if(aux[0]>='0' && aux[0]<='9')
{
///construiesc nrul
nr =0;
n=aux.length();
for(i=0;i<n;i++) nr=nr*10+(aux[i]-'0');
STN.push(nr);
}
else operatie(aux[0]);
FP.pop();
}
g<<STN.top()<<'\n';
f.close();
g.close();
return 0;
}