Pagini recente » Sandbox (cutiuţa cu năsip) | Cod sursa (job #1564633) | Istoria paginii runda/wellcodesimulareclasa9-10martie/clasament | Cod sursa (job #2069286) | Cod sursa (job #1759599)
#include<stdlib.h>
#include<fstream>
#include<iostream>
#include<stack>
#include<string.h>
#include<queue>
#include<sstream>
using namespace std;
char expr[100005];
string list[100005];
stack<string> postfix;
stack<string> stiva;
int nrs;
bool token(char c)
{
if(c=='+' || c=='*' || c=='(' || c==')' || c=='-' || c=='/')
return true;
return false;
}
void convertToList(char * str)
{
int len=strlen(str);
for(int i=0;i<len;i++)
{
string s="";
if(token(str[i]))
{
s+=str[i];
list[nrs++]=s;
//list.push(s);
}
else{
s+=str[i++];
while(!token(str[i]) && i<len)
{
s+=str[i++];
}
i--;
list[nrs++]=s;
// list.push(s);
};
}
}
int priority(string q)
{
char c=q.c_str()[0];
int p=0;
if(c=='+')
p=2;
else if(c=='-')
p=2;
else if(c=='*')
p=3;
else if(c=='/')
p=3;
else if(c=='(')
p=1;
else if(c==')')
p=1;
return p;
}
void myPush(string curent)
{
stack<string> st;
st=stiva;
if(curent==")")
{
int cont=-1;
while(cont<0)
{
string el=stiva.top();stiva.pop();
if(el=="(")
cont++;
else if(el==")")
cont--;
else
postfix.push(el);
}
}
else
{
if(curent!="(") {
string el = " ";
if (!stiva.empty())
el = stiva.top();
while (!stiva.empty() && priority(el) >= priority(curent)) {
postfix.push(el);
stiva.pop();
if (!stiva.empty())
el = stiva.top();
}
}
stiva.push(curent);
}
}
void transform()
{
int index=0;
while(index<nrs)
{
string el=list[index++];
if(token(el.c_str()[0]))
{
myPush(el);
}
else postfix.push(el);
}
while(!stiva.empty())
{
postfix.push(stiva.top());
stiva.pop();
}
}
int evaluate()
{
string el=postfix.top();postfix.pop();
if(token(el.c_str()[0]))
{
int x = evaluate();
int y = evaluate();
if(el=="/")
{
return y/x;
}
else if(el=="*")
{
return y*x;
}
else if(el=="+")
{
return y+x;
}
else if(el=="-")
{
return y-x;
}
}
return atoi(el.c_str());
}
int main()
{
fstream f,g;
f.open("evaluare.in",ios::in);
g.open("evaluare.out",ios::out);
f>>expr;
convertToList(expr);
transform();
int n=evaluate();
g<<n<<endl;
}