Pagini recente » Cod sursa (job #3134433) | Cod sursa (job #2496254) | Cod sursa (job #236868) | Monitorul de evaluare | Cod sursa (job #1214045)
#include <fstream>
#include <cstring>
#include <vector>
#define MX 100005
using namespace std;
// -1=+, -2=-, -3=*, -4=/
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int l;
char s[41];
vector<char> inf; //infix si stack
vector<int> pof,rez; //postfix si rezultatul final
void citire()
{
fin>>s;
l = strlen(s);
}
int numar(int &i)
{
int nr=0;
while(s[i]>='0' && s[i]<='9')
{
nr = nr*10 + s[i] - '0';
i++;
}
i--;
return nr;
}
void infix_to_postfix()
{
int i;
char x;
for(i=0; i<l; i++)
{
if(s[i]=='*' || s[i]=='/')
{
inf.push_back(s[i]);
}
else
if(s[i]=='+' || s[i]=='-')
{
if(!inf.empty())
{
x = inf.back();
while(x=='*' || x=='/')
{
inf.pop_back();
//pof.push_back(x);
if(x == '*') pof.push_back(-3);
else pof.push_back(-4);
x = inf.back();
}
}
inf.push_back(s[i]);
}
else
if(s[i]=='(')
{
inf.push_back(s[i]);
}
else
if(s[i]==')')
{
x = inf.back();
while(x != '(')
{
inf.pop_back();
//pof.push_back(x);
if(x == '+') pof.push_back(-1);
if(x == '-') pof.push_back(-2);
if(x == '*') pof.push_back(-3);
if(x == '/') pof.push_back(-4);
x = inf.back();
}
inf.pop_back();
}
else
{
pof.push_back(numar(i));
}
/*fout<<i;
fout.flush();*/
}
while(!inf.empty())
{
//pof.push_back(inf.back());
x = inf.back();
if(x == '+') pof.push_back(-1);
if(x == '-') pof.push_back(-2);
if(x == '*') pof.push_back(-3);
if(x == '/') pof.push_back(-4);
inf.pop_back();
}
//fout<<pof[5];
}
void postfix_to_rez()
{
vector<int>::iterator it;
int i,o1,o2;
for(it=pof.begin(); it!=pof.end(); it++)
{
if(*it >= 0)
{
rez.push_back(*it);
}
else
{
o1 = rez.back(); rez.pop_back();
o2 = rez.back(); rez.pop_back();
switch(*it)
{
case -1: rez.push_back((o2+o1) % 1000000000); break;
case -2: rez.push_back((o2-o1) % 1000000000); break;
case -3: rez.push_back((o2*o1) % 1000000000); break;
case -4: rez.push_back((o2/o1) % 1000000000); break;
}
}
}
}
int main()
{
citire();
infix_to_postfix(); //inf e gol, pof are postfix
postfix_to_rez();
fout<<rez[0];
pof.clear();
rez.clear();
fin.close(); fout.close();
return 0;
}