Pagini recente » Cod sursa (job #970101) | Cod sursa (job #1384362) | Cod sursa (job #436296) | Monitorul de evaluare | Cod sursa (job #2505090)
#include <iostream>
#include <fstream>
#include <queue>
#include <stack>
#include <string.h>
#include <string>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
queue<char> infix;
queue<string> postfix;
void toPostFix();
int priority(char c);
bool isOperand(char c);
int getNumber(string s);
int main(){
char s[100001];
in.getline(s, 100001);
for(int i = 0; i < strlen(s); i++){
infix.push(s[i]);
}
toPostFix();
bool b = false;
stack<int> stack;
while(!postfix.empty()){
string st = postfix.front();
postfix.pop();
int n = 0;
if(st == "+"){
int nr1 = stack.top(); stack.pop();
int nr2 = stack.top(); stack.pop();
n = nr1 + nr2;
stack.push(n);
} else if(st == "-"){
int nr2 = stack.top(); stack.pop();
int nr1 = stack.top(); stack.pop();
n = nr1 - nr2;
stack.push(n);
} else if(st == "*"){
int nr2 = stack.top(); stack.pop();
int nr1 = stack.top(); stack.pop();
n = nr1 * nr2;
stack.push(n);
} else if(st == "/"){
int nr2 = stack.top(); stack.pop();
int nr1 = stack.top(); stack.pop();
n = nr1 / nr2;
stack.push(n);
} else {
int nr = getNumber(st);
stack.push(nr);
}
}
out<<stack.top();
return 0;
}
void toPostFix(){
stack<char> s;
while(!infix.empty()){
char c = infix.front();
infix.pop();
if(isOperand(c)){
int n = (c - '0');
while(isOperand(infix.front())){
int ch = infix.front();
n = n * 10 + (int)(ch - '0');
infix.pop();
}
string st = to_string(n);
postfix.push( st );
} else if(c == '('){
s.push(c);
} else if(c == ')') {
while(s.top() != '('){
string st(1, s.top());
postfix.push( st );
s.pop();
}
s.pop();
} else {
while( !s.empty() && priority(s.top()) >= priority(c) ){
string st(1, s.top());
postfix.push( st );
s.pop();
}
s.push(c);
}
}
while(!s.empty()){
string st(1, s.top());
postfix.push( st );
s.pop();
}
}
bool isOperand(char c){
if(strchr("+-*/^()", c) != NULL){
return false;
}
return true;
}
int priority(char c){
if(c == '+' || c == '-')
return 1;
if(c == '*' || c == '/')
return 2;
if(c == '^')
return 3;
return -1;
}
int getNumber(string s){
int n = 0;
char ch[100] = "";
strcpy(ch, s.c_str());
for(int i = 0; i < s.length(); i++){
int d = ch[i] - '0';
n = n * 10 + d;
}
return n;
}