Pagini recente » Cod sursa (job #204797) | Cod sursa (job #415377) | Cod sursa (job #2415672) | Cod sursa (job #1423446) | Cod sursa (job #2315513)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int fp[100005]; //forma poloneza
char ex[100005];
stack<int>S;
stack<char>st;
int lg,poz,vec[100005];
void Forma()
{ char op; int nr;
for(int i=0;i<lg;i++)
{
if(isdigit(ex[i]))
{ nr=0;
while(isdigit(ex[i])) // form numar
{nr=nr*10+ex[i]-'0';i++;}
i--; //de la for
fp[poz++]=nr;
} //operand
else //operator
if(!st.empty())
{ st.push(ex[i]);// pun op
op=st.top(); //st.pop();
if(op=='*' || op=='/') ///prior 1
{ st.pop();
if(st.top()=='*' || st.top()=='/') ///prior 1
{if(st.top()=='*') fp[poz]=-3;
else fp[poz]=-4;
vec[poz]=1; poz++; st.pop();
st.push(op);
}
else st.push(op);
}
else if(op=='+' || op=='-') ///prior 2
{st.pop();
if(st.top()=='*' || st.top()=='/' || st.top()=='-' ||st.top()=='+') ///prior 1 sau 2
{
if(st.top()=='*') fp[poz]=-3;
else if(st.top()=='/') fp[poz]=-4;
else if(st.top()=='+') fp[poz]=-1;
else fp[poz]=-2;
vec[poz]=1; poz++; st.pop();
st.push(op);
//fout<<poz;
}
else st.push(op);
}
else if(op==')')
{
st.pop();
while(st.top()!='(')
{ if(st.top()=='*') fp[poz]=-3;
else if(st.top()=='/') fp[poz]=-4;
else if(st.top()=='+') fp[poz]=-1;
else fp[poz]=-2;
vec[poz]=1; poz++; st.pop();}
st.pop(); //parant deschisa
}
}
else st.push(ex[i]);
}
while(!st.empty()) //mut restul
{
if(st.top()=='*') fp[poz]=-3;
else if(st.top()=='/') fp[poz]=-4;
else if(st.top()=='+') fp[poz]=-1;
else fp[poz]=-2; vec[poz]=1; poz++; st.pop();
}
}
void Af()
{ //fout<<fp[0]<<"\n";
for(int i=0;i<poz;i++)
fout<<fp[i]<<" ";
}
void Calcul()
{ int op; int nr1,nr2;
for(int i=0;i<poz;i++)
if(vec[i]==0) //nu e semn
{
S.push(fp[i]);
}
else
{
op=fp[i];
nr1=S.top();S.pop();
nr2=S.top(); S.pop();
if(op==-1) S.push(nr1+nr2);
else if(op==-2) S.push(nr2-nr1);
else if(op==-3) S.push(nr1*nr2);
else if(op==-4) S.push(nr2/nr1);
}
fout<<S.top(); //rez
}
int main()
{ fin>>ex;
lg=strlen(ex);
Forma(); //f poloneza
//Af();
//fout<<"\n";
Calcul(); //eval expresie
return 0;
}