Pagini recente » Cod sursa (job #2180392) | Cod sursa (job #2155598) | Cod sursa (job #1981592) | Cod sursa (job #1351052) | Cod sursa (job #672938)
Cod sursa(job #672938)
/**
Author: Mihai Morcov
Project name:
Started at: 03.02.2012 13:20:38
Ended at: 03.02.2012 14:48:56
*/
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <stack>
#define nn 100010
using namespace std;
FILE * f = fopen("evaluare.in","r");
FILE * g = fopen("evaluare.out","w");
char op[10] = "+-*/";
char in[nn];
int lg,top;
struct post{
char s[100];
} po[100000];
struct stiva{
char s[100];
} st[100000];
stack <long long> S;
int in_prior(char x)
{
if(x=='+' || x=='-')
return 1;
if(x=='*' || x=='/')
return 3;
if(x=='(')
return 9;
if(x==')')
return 0;
return 8;
}
int st_prior(char x)
{
if(x=='+' || x=='-')
return 2;
if(x=='*' || x=='/')
return 4;
if(x=='(')
return 0;
if(x=='#')
return -1;
}
void infix2postfix()
{
//cout << "\n Infix: "<<in<<"\n";
int p = 0;
top = -1;
*st[++top].s = '#';
for(int i=0;i<strlen(in);i++)
{
char c[10]; memset(c,0,10);
*c = in[i];
if(isdigit(c[0]))
{
char nr[100];
memset(nr,0,sizeof(nr));
int l=0;
while(isdigit(*c))
{
nr[l++] = *c;
i++;
*c = in[i];
}
//po[lg++] = nr+'0';
strcpy(po[lg++].s, nr);
i--;
}
else
{
while(st_prior( *st[top].s) > in_prior(*c))
{
*po[lg++].s = *st[top].s;
top--;
}
if( st_prior( *st[top].s) != in_prior( *c) )
{
*st[++top].s= *c;
}
else
{
top--;
}
}
}
while( *st[top].s !='#')
{
*po[lg++].s = *st[top].s;
top--;
}
// cout << " Postfix: ";
// for(int i=0;i<lg;i++)
// cout << po[i].s<<" ";
}
long long numar(char q[20])
{
long long rez=0;
for(int i=0;i<strlen(q);i++)
rez = rez * 10 +(q[i]-'0');
return rez;
}
long long operatie( int a, int b, char o )
{
switch( o ) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}
void eval_postfix()
{
for(int i=0;i<lg;i++)
{
if(strchr(op, *po[i].s))
{
long long x2 = S.top();
S.pop();
long long x1 = S.top();
S.pop();
S.push(operatie(x1,x2,*po[i].s));
}
else
{
S.push(numar(po[i].s));
}
}
fprintf(g,"%ld", S.top());
}
void citire()
{
fgets(in,nn,f);
in[strlen(in)-1]=0;
}
int main()
{
citire();
infix2postfix();
eval_postfix();
return 0;
}