Pagini recente » Cod sursa (job #1338436) | Cod sursa (job #2057051) | Cod sursa (job #2138439) | Cod sursa (job #2770543) | Cod sursa (job #2220636)
#include <iostream>
#include <fstream>
#include <string.h>
#include <string>
#include <vector>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
char s[100005];
int x, n;
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() != '^'))){
rez.push_back(calculate(st.back()));
st.pop_back();
}
if(s[i] == '(')
st.push_back(s[i]);
else if(s[i] == ')'){
while(st.back() != '('){
rez.push_back(calculate(st.back()));
st.pop_back();
}
st.pop_back();
}else st.push_back(s[i]);
}
}
while(!st.empty()){
rez.push_back(calculate(st.back()));
st.pop_back();
}
g<<rez.back();
return 0;
}