Pagini recente » Cod sursa (job #1544076) | Cod sursa (job #1676181) | Cod sursa (job #1650389) | Cod sursa (job #1255342) | Cod sursa (job #1160875)
#include <fstream>
#include <string>
#include <vector>
#include <stack>
#define OPEN 1000000001
#define CLOSE 1000000002
#define STAR 1000000003
#define DIV 1000000004
#define PLUS 1000000005
#define MINUS 1000000006
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char akt;
vector<int> base, expr;
vector<int> format (const vector<int>& x)
{
stack<int> temp;
vector<int> kif;
for (vector<int>::const_iterator i = x.begin(); i<x.end(); i++)
{
if (*i == OPEN) temp.push (OPEN);
else if (*i == CLOSE)
{
while (temp.top() != OPEN)
{
kif.push_back(temp.top());
temp.pop();
}
temp.pop();
}
else if (*i == PLUS)
{
while (temp.top() != OPEN)
{
kif.push_back(temp.top());
temp.pop();
}
temp.push(PLUS);
}
else if (*i == MINUS)
{
while (temp.top() != OPEN)
{
kif.push_back(temp.top());
temp.pop();
}
temp.push(MINUS);
}
else if (*i == STAR)
{
while (temp.top() != PLUS && temp.top() != MINUS && temp.top() != OPEN)
{
kif.push_back(temp.top());
temp.pop();
}
temp.push(STAR);
}
else if (*i == DIV)
{
while (temp.top() != PLUS && temp.top() != MINUS && temp.top() != OPEN)
{
kif.push_back(temp.top());
temp.pop();
}
temp.push(DIV);
}
else kif.push_back(*i);
}
return kif;
}
int evaluate (const vector<int>& x)
{
stack<int> temp;
int t = 0;
for (vector<int>::const_iterator i = x.begin(); i<x.end(); i++)
{
if (*i == PLUS)
{
t = temp.top(); temp.pop();
temp.top() += t;
}
else if (*i == MINUS)
{
t = temp.top(); temp.pop();
temp.top() -= t;
}
else if (*i == STAR)
{
t = temp.top(); temp.pop();
temp.top() *= t;
}
else if (*i == DIV)
{
t = temp.top(); temp.pop();
temp.top() /= t;
}
else temp.push(*i);
}
return temp.top();
}
void write_vector (const vector<int>& temp)
{
for (vector<int>::const_iterator i = temp.begin(); i<temp.end(); i++)
if (*i == PLUS) g << '+';
else if (*i == MINUS) g << '-';
else if (*i == STAR) g << "*";
else if (*i == DIV) g << "/";
else g << *i << " ";
g << "\n";
}
int main()
{
base.push_back(OPEN);
while(f >> akt)
{
if (akt == '(') base.push_back (OPEN);
else if (akt == ')') base.push_back (CLOSE);
else if (akt == '*') base.push_back (STAR);
else if (akt == '/') base.push_back (DIV);
else if (akt == '+') base.push_back (PLUS);
else if (akt == '-') base.push_back (MINUS);
else
{
base.push_back (akt-'0');
while (f.peek()>= '0' && f.peek()< '10')
{
f >> akt;
base[base.size()-1] = base.back() * 10 + akt - '0';
}
}
}
base.push_back(CLOSE);
expr = format (base);
//write_vector (expr);
g << evaluate (expr);
}