Cod sursa(job #2315895)
Utilizator | Data | 10 ianuarie 2019 19:09:35 | |
---|---|---|---|
Problema | Evaluarea unei expresii | Scor | 0 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 3.67 kb |
#include <fstream>
#include <string>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
stack <char>operatori;
stack <int>numere;
//un operator se adauga in varful stivei daca :
//1. stiva este goala
//2. in varful stivei este '('
//3. in varful stivei este un operator cu prioritate strict mai mica decat operatorul curent
inline int prio(char ch)
{
switch(ch)
{
case '*': return 3;
case '/': return 2;
case '-': return 1;
case '+': return 5;
default: return 4;
}
}
int main()
{
long long nr=0, nr1=0, nr2=0;
char ch;
fin>>s;
operatori.push('(');
s.push_back(')');
for(int i=0;i<s.size();i++)
{
// if(!numere.empty())
//fout<<numere.top()<<"\n";
if(s[i]>='0' and s[i]<='9')
{
nr=0;
while(s[i]>='0' and s[i]<='9')
{
nr=nr*10+(s[i]-'0');
i++;
}
i--;
numere.push(nr);
continue;
}
else
{
if(s[i]=='(')
{
operatori.push(s[i]);
continue;
}
else
{
if(s[i]==')')
{
while(operatori.top()!='(')
{
nr1=numere.top();
numere.pop();
nr2=numere.top();
numere.pop();
ch=operatori.top();
operatori.pop();
if(ch=='+')
{
nr1=nr2+nr1;
}
if(ch=='-')
{
nr1=nr2-nr1;
}
if(ch=='*')
{
nr1=nr1*nr2;
}
if(ch=='/')
{
nr1=nr2/nr1;
}
numere.push(nr1);
}
operatori.pop();
continue;
}
else
{
ch=s[i];
if(prio(ch)>prio(operatori.top()))
{
operatori.push(s[i]);
continue;
}
else
{
nr1=0;
i++;
while(s[i]>='0' and s[i]<='9')
{
nr1=nr1*10+(s[i]-'0');
i++;
}
i--;
nr2=numere.top();
numere.pop();
if(ch=='+')
{
nr1=nr2+nr1;
}
if(ch=='-')
{
nr1=nr2-nr1;
}
if(ch=='*')
{
nr1=nr1*nr2;
}
if(ch=='/')
{
nr1=nr2/nr1;
}
numere.push(nr1);
continue;
}
}
}
}
}
fout<<numere.top()<<"\n";
return 0;
}