Pagini recente » Cod sursa (job #480135) | Cod sursa (job #1024319) | Cod sursa (job #2045003) | Cod sursa (job #2392871) | Cod sursa (job #2048573)
#include<fstream>
#include<cstring>
#include<stack>
#include<vector>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int P[130], n;
char s[100005];
stack<char> stiva;
stack<int> S;
vector< pair<int,int> > v;
int op( int a, int b, char c ){
if( c == '+' )
return a + b;
if( c == '-' )
return a - b;
if( c == '*' )
return a * b;
if( c == '/' )
return a / b;
}
int main(){
P[(int)('+')] = P[(int)('-')] = 1;
P[(int)('*')] = P[(int)('/')] = 2;
fin >> s;
n = strlen(s);
for( int i = 0; i < n; i++ ){
if( s[i] == '(' ){
stiva.push( s[i] );
continue;
}
if( s[i] == ')' ){
while( stiva.top() != '(' ){
v.push_back( make_pair( 0, (int)( stiva.top() ) ) );
stiva.pop();
}
stiva.pop();
continue;
}
if( s[i] == '+' ){
if( i == 0 || s[i - 1] == '(' )
v.push_back( make_pair( 1, 0 ) );
while( !stiva.empty() && P[(int)(stiva.top())] >= P[(int)(s[i])] ){
v.push_back( make_pair( 0, (int)( stiva.top() ) ) );
stiva.pop();
}
stiva.push( s[i] );
continue;
}
if( s[i] == '-' ){
if( i == 0 || s[i - 1] == '(' )
v.push_back( make_pair( 1, 0 ) );
while( !stiva.empty() && P[(int)(stiva.top())] >= P[(int)(s[i])] ){
v.push_back( make_pair( 0, (int)( stiva.top() ) ) );
stiva.pop();
}
stiva.push( s[i] );
continue;
}
if( s[i] == '*' ){
while( !stiva.empty() && P[(int)(stiva.top())] >= P[(int)(s[i])] ){
v.push_back( make_pair( 0, (int)( stiva.top() ) ) );
stiva.pop();
}
stiva.push( s[i] );
continue;
}
if( s[i] == '/' ){
while( !stiva.empty() && P[(int)(stiva.top())] >= P[(int)(s[i])] ){
v.push_back( make_pair( 0, (int)( stiva.top() ) ) );
stiva.pop();
}
stiva.push( s[i] );
continue;
}
int nr = 0;
while( s[i] >= '0' && s[i] <= '9' ){
nr = nr * 10 + ( s[i] - '0' );
i++;
}
v.push_back( make_pair( 1, nr ) );
i--;
}
while( !stiva.empty() ){
v.push_back( make_pair( 0, (int)( stiva.top() ) ) );
stiva.pop();
}
// 1 1 + 13 * 10 2 / +
for( int i = 0; i < v.size(); i++ ){
if( v[i].first == 1 )
S.push( v[i].second );
else{
int a, b;
a = S.top();
S.pop();
b = S.top();
S.pop();
S.push( op( b, a, (char)(v[i].second) ) );
}
}
fout << S.top() << "\n";
return 0;
}