Cod sursa(job #3366798)
| Utilizator | Data | 4 octombrie 2026 12:58:08 | |
|---|---|---|---|
| Problema | Evaluarea unei expresii | Scor | 100 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 2.3 kb |
#include<bits/stdc++.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
const int inm=1e9+1, dv=1e9+2, pd=1e9+3, mns=1e9+4;
int main()
{
string e;
fin >> e;
stack<int>st;
for(int i=0; i<e.size(); i++)
{
if(e[i]=='-')
st.push(mns);
else if(e[i]=='*')
st.push(inm);
else if(e[i]=='(')
st.push(pd);
else if(e[i]=='/')
st.push(dv);
else if(e[i]>='0' && e[i]<='9')
{
int x=0;
while(i<e.size() && e[i]>='0' && e[i]<='9')
{
x*=10;
x+=e[i]-'0';
i++;
}
i--;
if(st.empty())
st.push(x);
else if(st.top()==mns)
{
st.pop();
st.push(-x);
}
else if(st.top()==inm)
{
st.pop();
int y=st.top();
st.pop();
st.push(x*y);
}
else if(st.top()==dv)
{
st.pop();
int y=st.top();
st.pop();
st.push(y/x);
}
else
st.push(x);
}
else if(e[i]==')')
{
int sum=0;
while(!st.empty() && st.top()!=pd)
{
sum+=st.top();
st.pop();
}
st.pop();
if(st.empty()){
st.push(sum);
}
else if(st.top()==mns)
{
st.pop();
st.push(-sum);
}
else if(st.top()==inm)
{
st.pop();
int y=st.top();
st.pop();
st.push(sum*y);
}
else if(st.top()==dv)
{
st.pop();
int y=st.top();
st.pop();
st.push(y/sum);
}
else{
st.push(sum);
}
}
}
int sum=0;
while(!st.empty())
{
sum+=st.top();
st.pop();
}
fout << sum;
return 0;
}
