Cod sursa(job #690924)

Utilizator costyv87Vlad Costin costyv87 Data 26 februarie 2012 01:22:06
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#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=='*' || 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]==')') {
		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;
}