Pagini recente » Profil UAIC_Buruiana_Oprea_Ouatu | Cod sursa (job #1550086) | Cod sursa (job #2910728) | Cod sursa (job #2121889) | Cod sursa (job #690925)
Cod sursa(job #690925)
#include <cstdio>
#include <stack>
#include <string.h>
FILE *f,*g;
using namespace std;
char a[100100];
struct cp{bool k; int x;} p[100100];
stack<int> s;
int i,nn;
inline int val(char c) {
switch (c) {
case '-' :return 1;
case '+' :return 2;
case '*' :return 3;
case '/' :return 4;
case '(' : return 0;
break;
}
}
inline char inv(int x) {
switch (x) {
case 1 :return '-';
case 2 :return '+';
case 3 :return '*';
case 4 :return '/';
case 5 : return '(';
break;
}
}
inline int sol(int x1,int x2,int c) {
switch (c) {
case 1 :return x1-x2;
case 2 :return x1+x2;
case 3 :return x1*x2;
case 4 :return x1/x2;
break;
}
}
inline int semn(char c) {
if (c=='+' || c=='-' || c=='*' || c=='/') return 1;
return 0;
}
inline int cif(char c) {
if (c>='0' && c<='9') return 1;
return 0;
}
void transf() {
int n=strlen(a)-1;
for (i=0;i<=n;i++) {
if (cif(a[i])) {
p[++nn].k=true;
p[nn].x=0;
while (cif(a[i]) && i<=n)
p[nn].x=p[nn].x*10+(a[i++]-'0');
i--;
continue;
}
if (a[i]=='(') {
s.push(a[i]);
}
if (a[i]==')') {
while (s.top()!='(') {
p[++nn].k=false;
p[nn].x=val(s.top());
s.pop();
}
s.pop();
continue;
}
if (semn(a[i])) {
if (s.empty())
s.push(a[i]);
else {
while (!s.empty() && val(s.top())>=val(a[i])) {
p[++nn].k=false;
p[nn].x=val(s.top());
s.pop();
}
s.push(a[i]);
}
continue;
}
}
while (!s.empty()) {
p[++nn].k=false;
p[nn].x=val(s.top());
s.pop();
}
/*for (i=1;i<=nn;i++)
if (p[i].k)
fprintf(g,"%d ",p[i].x);
else
fprintf(g,"%c ",inv(p[i].x));*/
}
void solve() {
int i,x1,x2;
for (i=1;i<=nn;i++) {
if (p[i].k==true)
s.push(p[i].x);
else {
x1=s.top();
s.pop();
x2=s.top();
s.pop();
s.push(sol(x2,x1,p[i].x));
}
}
fprintf(g,"%d",s.top());
}
int main() {
f=fopen("evaluare.in","r");
g=fopen("evaluare.out","w");
fscanf(f,"%s",a);
for (i=strlen(a);a[i-1]==' ' || a[i-1]=='\n';i--);
a[i]='\0';
transf();
solve();
fclose(g);
return 0;
}