Pagini recente » Cod sursa (job #1510536) | Cod sursa (job #1679663) | Cod sursa (job #1487790) | Cod sursa (job #2337281) | Cod sursa (job #1940347)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char infix[100005];
queue<char> postfix;
stack<char> semn;
inline int priority(char x) {
switch(x) {
case '*': return 2;
case '/': return 2;
case '%': return 2;
case '+': return 1;
case '-': return 1;
default: return 0;
}
}
inline bool isDigit(char x) {
return (x>='0'&&x<='9');
}
void infixToPostfix() {
char* i = &infix[0];
while(*i!='\0') {
while(*i==' '||*i=='\t') i++;
if(isDigit(*i)) {
postfix.push(*i);
i++;
continue;
}
postfix.push(' ');
if(*i=='(') {
semn.push(*i);
i++;
continue;
}
if(*i==')') {
while(semn.top()!='(') {
postfix.push(semn.top());
semn.pop();
}
semn.pop(); //scoatem pe '('
i++;
continue;
}
if(!isDigit(*i)) {
if(semn.empty()) {
semn.push(*i);
i++;
continue;
}
while(semn.size()&&priority(semn.top())>=priority(*i)) {
postfix.push(semn.top());
semn.pop();
}
semn.push(*i);
i++;
}
}
postfix.push(' ');
for(;semn.size();semn.pop()) postfix.push(semn.top());
}
inline int doMath(int x,int y,char op) {
switch(op) {
case '+':return x+y;
case '-':return x-y;
case '*':return x*y;
case '/':return x/y;
case '%':return x%y;
}
}
int main()
{
fin>>infix;
infixToPostfix();
int buffer=-1;
stack<int> aux;
for(;postfix.size();postfix.pop()) {
char cChar = postfix.front();
if(isdigit(cChar)) {
if(buffer==-1) buffer=0;
buffer=buffer*10+(cChar-'0');
continue;
}
else if(cChar==' ') {
if(buffer==-1) continue;
aux.push(buffer);
buffer=-1;
continue;
}
else {
int nr1=aux.top();
aux.pop();
int nr2=aux.top();
aux.pop();
aux.push(doMath(nr2,nr1,cChar));
continue;
}
}
fout<<aux.top();
return 0;
}