Pagini recente » Cod sursa (job #317448) | Cod sursa (job #2616462) | Cod sursa (job #1849755) | Cod sursa (job #1428562) | Cod sursa (job #2220647)
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char s[100005];
int x, n, aux;
vector<char> st;
vector<int> rez;
int calculate(char ch){
int x = 0, y = 0, z = 1;
x = rez.back();
rez.pop_back();
y = rez.back();
rez.pop_back();
switch(ch){
case '^':
while(x){
if(x % 2) z *= y;
else {
y *= y;
x /= 2;
}
}
return z;
case '*':
return y*x;
case '/':
return y/x;
case '+':
return y + x;
case '-':
return y - x;
default : break;
}
return 0;
}
int grade(char ch){
switch(ch){
case '^': return 4;
case '/': return 3;
case '*': return 3;
case '-': return 2;
case '+': return 2;
default: break;
}
return 0;
}
int main()
{
f.getline(s, 100005);
n = strlen(s);
for(int i = 0; i < n; i++){
while(s[i] >= '0' && s[i] <= '9' && i < n){
x = x*10 + (s[i] - '0');
i++;
}
if(x){
i--;
rez.push_back(x);
x = 0;
}else{
while(!st.empty() && st.back() != '(' && (grade(st.back()) > grade(s[i]) || (grade(st.back()) == grade(s[i]) && st.back() != '^'))){
aux = calculate(st.back());
rez.push_back(aux);
st.pop_back();
}
if(s[i] == '(')
st.push_back(s[i]);
else if(s[i] == ')'){
while(st.back() != '('){
aux = calculate(st.back());
rez.push_back(aux);
st.pop_back();
}
st.pop_back();
}else st.push_back(s[i]);
}
}
while(!st.empty()){
aux = calculate(st.back());
rez.push_back(aux);
st.pop_back();
}
g<<rez.back();
return 0;
}