Pagini recente » Cod sursa (job #1649916) | Cod sursa (job #853245) | Cod sursa (job #2171788) | Cod sursa (job #1224135) | Cod sursa (job #2919277)
#include<bits/stdc++.h>
#define loop(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
#define ar array
#define ln '\n';
#define pb push_back
#define p push
#define cin f
#define cout g
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
string s;
stack<int> val,op;
int precedence(char x){
if(x=='+'||x=='-')return 1;
else if(x=='*'||x=='/')return 2;
return 0;
}
int calculefectiv(int a,int b,char semn){
if(semn=='+')return a+b;
else if(semn=='-')return a-b;
else if(semn=='*')return a*b;
else return a/b;
}
int calcul(string s){
for(int i=0;s[i];i++){
if(s[i]>='0'&&s[i]<='9'){
int x=0;
while(s[i]>='0'&&s[i]<='9'){
x=x*10+(s[i]-'0');
i++;
}
i--;
val.p(x);
}
else if(s[i]=='(')op.push(s[i]);
else if(s[i]==')'){
while(op.top()!='('){
int a=val.top();val.pop();
int b=val.top();val.pop();
char semn=op.top();op.pop();
int ans=calculefectiv(a,b,semn);
val.p(ans);
}
op.pop();
}
else{
while(!op.empty()&&precedence(op.top())>=precedence(s[i])){
int a=val.top();val.pop();
int b=val.top();val.pop();
int rez=calculefectiv(a,b,op.top());
val.p(rez);
op.pop();
}
op.push(s[i]);
}
}
while(!op.empty()){
int a=val.top();val.pop();
int b=val.top();val.pop();
int rez=calculefectiv(a,b,op.top());
val.p(rez);
op.pop();
}
return val.top();
}
int main(){
cin>>s;
cout<<calcul(s);
}
/**
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
ifstream fi("date.in");
ofstream fo("date.out");
string s;
stack <int>val,op;
int precedence(char sign)
{
if(sign=='+' || sign=='-')
return 1;
if(sign=='*' || sign=='/')
return 2;
return 0;
}
int calculEfectiv(int a,int b,char semn)
{
if(semn=='+')
return a+b;
else if(semn=='-')
return a-b;
else if(semn=='*')
return a*b;
else
return a/b;
}
int calcul(string s)
{
int index=0;
while(index<s.length())
{
if(s[index]==' ')
continue;
if(s[index]>='0' && s[index]<='9')
{
int numar=0;
while(s[index]>='0' && s[index]<='9')
{
numar=numar*10+(s[index]-'0');
index++;
}
val.push(numar);
index--;
}else if(s[index]=='(')
op.push(s[index]);
else if(s[index]==')')
{
while(!op.empty() && op.top()!='(')
{
int a=val.top();
val.pop();
int b=val.top();
val.pop();
char semn=op.top();
op.pop();
int rez=calculEfectiv(b,a,semn);
val.push(rez);
}
op.pop();
}else
{
while(!op.empty() && precedence(op.top())>=precedence(s[index]))
{
int a=val.top();
val.pop();
int b=val.top();
val.pop();
int rez=calculEfectiv(b,a,op.top());
val.push(rez);
op.pop();
}
op.push(s[index]);
}
index++;
}
while(!op.empty())
{
int a=val.top();
val.pop();
int b=val.top();
val.pop();
int rez=calculEfectiv(b,a,op.top());
op.pop();
val.push(rez);
}
return val.top();
}
int main()
{
fi>>s;
fo<<calcul(s);
return 0;
}
*/