Pagini recente » Cod sursa (job #29862) | Cod sursa (job #131932) | Cod sursa (job #2484231) | Cod sursa (job #188123) | Cod sursa (job #376454)
Cod sursa(job #376454)
#include <stdio.h>
#define N 100000
struct stiva
{char bit;//1 numar 0 operator
union
{int nr;
char c;
}data;
};
stiva st[N];int vf1;
char op[N]; int pop[N],vf2;
int temp[N],vf3;
int main ()
{FILE *fin=fopen("evaluare.in","r");
FILE *fout=fopen("evaluare.out","w");
char c;
char lop[5]={'+','-','/','*','~'};
int pri[5]={1,1,2,2,3};
int i,flag,offset=0,nr,nar=2,p;//2 daca e unar
int estenr=0; //0 daca e binar
vf1=vf2=0; //cu atat se mareste prioritatea
nr=0;
do
{c=fgetc(fin);
if(c>='0'&&c<='9')
{nr=nr*10+c-'0';
estenr=1;
}
else
{if(estenr)
{st[++vf1].bit=1;
st[vf1].data.nr=nr;
nr=0;
estenr=0;
nar=0;
}
for (i=0,flag=0;i<4;i++)
{if(lop[i]==c)
{flag=1;
break;
}
}
if(flag==1)
{if(c=='-'&&nar)
p=offset+3;
else
p=offset+pri[i];
while(vf2>0&&pop[vf2]>=p)
{st[++vf1].bit=0;
st[vf1].data.c=op[vf2--];
}
if(c=='-'&&nar)c='~';
op[++vf2]=c;
pop[vf2]=p;
nar=2;
}
else
{if(c=='(')
{offset+=3;
nar=2;
}
else if(c==')')
{offset-=3;
nar=0;
}
}
}
}
while(c!=EOF);
while(vf2>0)
{st[++vf1].bit=0;
st[vf1].data.c=op[vf2--];
}
/*
for (i=1;i<=vf1;i++)
{if(st[i].bit==1)
fprintf(fout,"%d",st[i].data.nr);
else
fprintf(fout,"%c",st[i].data.c);
}
*/
vf3=0;
i=1;
while(i<=vf1)
{while(i<=vf1&&st[i].bit)//e numar
{temp[++vf3]=st[i++].data.nr;
}
if(vf1>0)
{switch(st[i].data.c)
{case '+':temp[vf3-1]=temp[vf3-1]+temp[vf3];vf3--;break;
case '-':temp[vf3-1]=temp[vf3-1]-temp[vf3];vf3--;break;
case '*':temp[vf3-1]=temp[vf3-1]*temp[vf3];vf3--;break;
case '/':temp[vf3-1]=temp[vf3-1]/temp[vf3];vf3--;break;
case '~':temp[vf3]=-temp[vf3];break;
}
}
i++;
}
fprintf(fout,"%d",temp[1]);
return 0;
}