Pagini recente » Cod sursa (job #252904) | Cod sursa (job #1033695) | Cod sursa (job #89010) | Cod sursa (job #1683310) | Cod sursa (job #2857419)
#include <bits/stdc++.h>
using namespace std;
ifstream f("grader_test3.in");
ofstream g("evaluare.out");
stack <int> nr;
stack <char> op;
char sir[100001];
void eval()
{
int x=nr.top();
nr.pop();
int y=nr.top();
nr.pop();
char c;
c=op.top();
op.pop();
// cout<<'\n'<<"op: "<<(char)c<<'\n';
if(c=='+') nr.push(x+y);
else if(c=='-') nr.push(y-x);
else if(c=='*') nr.push(y*x);
else nr.push(y/x);
//cout<<"x="<<x<<'\n'<<"y="<<y<<'\n'<<"nr="<<nr.top()<<'\n'<<'\n';
}
void print(stack<int> nr, stack<char> op)
{
cout << "nr: ";
while (!nr.empty())
{
cout << nr.top() << " ";
nr.pop();
}
cout << "\nop:";
while (!op.empty())
{
cout << op.top() << " ";
op.pop();
}
cout << "\n";
}
int rez(char s[100005], int k)
{
int n=k;
for(int i=0; i<n; i++)
{
if(isdigit(s[i]))
{
int x=0;
while(i<n && isdigit(s[i]))
{
x=x*10+s[i]-'0';
i++;
}
i--;
nr.push(x);
// cout<<"x= "<<x<<'\n';
}
else if(s[i]=='(') op.push(s[i]);
else if(s[i]==')' && !op.empty())
{
if(op.top()=='(') op.pop();
else
{
while(op.top()!='(') eval();
op.pop();
}
}
else if(op.empty()) op.push(s[i]);
else if(s[i]=='*')
{
while(!op.empty() && op.top()=='/') eval();
op.push(s[i]);
}
else if(s[i]=='/')
{
while(!op.empty() && (op.top()=='*' || op.top()=='/')) eval();
op.push(s[i]);
}
else if(s[i]=='-')
{
while(!op.empty() && (op.top()=='*' || op.top()=='/' || op.top()=='-')) eval();
op.push(s[i]);
}
else if(s[i]=='+')
{
while(!op.empty() && (op.top()=='*' || op.top()=='/' || op.top()=='-')) eval();
op.push(s[i]);
}
print(nr, op);
}
while(!op.empty()) eval();
return nr.top();
}
int main()
{
f>>sir;
g<<rez(sir, strlen(sir));
return 0;
}