Cod sursa(job #2712340)
Utilizator | Data | 25 februarie 2021 17:41:50 | |
---|---|---|---|
Problema | Evaluarea unei expresii | Scor | 80 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 4.66 kb |
#include <bits/stdc++.h>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
stack <int> st1;
stack < pair <string,int> > st2;
map <string, int> m;
const int DIM = 1e5 + 7;
int op1(int x,int y)
{
return x + y;
}
int op2(int x,int y)
{
return x - y;
}
int op3(int x,int y)
{
return x * y;
}
int op4(int x,int y)
{
return x / y;
}
void eroare()
{
cout <<"Expresia nu este bine formata";
exit(0);
}
int main()
{
char s[DIM];
in.get(s,DIM);
m["*"] = 2;
m["/"] = 2;
m["+"] = 1;
m["-"] = 1;
m["#"] = 0;
int cnt = 0;
st2.push({"#",cnt});
s[strlen(s)] = '#';
for(int i = 0; i < strlen(s); i++)
{
if(s[i] == ' ')
continue;
string s1;
if(s[i] == '(')
{
cnt++;
}
else
if(s[i] == ')')
{
cnt--;
if(cnt < 0)
eroare();
}
else
if((s[i] >= '0' && s[i] <= '9'))
{
int nr = int(s[i])- int('0');
i++;
while(i < strlen(s) && (s[i] >= '0' && s[i] <= '9'))
{
nr = nr * 10 + int(s[i]) - '0';
i++;
}
i--;
st1.push(nr);
}
else
{
s1.push_back(s[i]);
int val = m[s1] + cnt * 5;
int valtop = m[st2.top().first] + 5 * st2.top().second;
if(val > valtop)
{
st2.push({s1,cnt});
}
else
{
while(st2.top().first != "#" && st2.top().second * 5 + m[st2.top().first] >= val)
{
string s3 = st2.top().first;
int valf;
if(s3 == "+")
{
if(st1.empty())
eroare();
int val1 = st1.top();
st1.pop();
if(st1.empty())
eroare();
int val2 = st1.top();
st1.pop();
valf = op1(val2,val1);
}
else
if(s3 == "-")
{
if(st1.empty())
eroare();
int val1 = st1.top();
st1.pop();
if(st1.empty())
valf = -val1;
else
{
int val2 = st1.top();
st1.pop();
valf = op2(val2,val1);
}
}
else
if(s3 == "*")
{
if(st1.empty())
eroare();
int val1 = st1.top();
st1.pop();
if(st1.empty())
eroare();
int val2 = st1.top();
st1.pop();
valf = op3(val2,val1);
}
else
{
if(st1.empty())
eroare();
int val1 = st1.top();
st1.pop();
if(st1.empty())
eroare();
int val2 = st1.top();
st1.pop();
valf = op4(val2,val1);
}
st1.push(valf);
st2.pop();
}
st2.push({s1,cnt});
}
}
}
if(st2.top().first != "#")
eroare();
st2.pop();
if(st2.top().first != "#")
eroare();
st2.pop();
if(!st2.empty())
eroare();
if(st1.empty())
eroare();
int rez = st1.top();
st1.pop();
if(!st1.empty())
eroare();
if(cnt != 0)
eroare();
out << rez;
return 0;
}