Cod sursa(job #84427)

Utilizator floringh06Florin Ghesu floringh06 Data 14 septembrie 2007 23:45:20
Problema Bool Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.8 kb
#include<stdio.h>

char pol[1005];
int np=0,v[100];

int alpha(char x)
{return (x>='A'&&x<='Z');}

int grad(char x)
{
if(x=='(') return 0;
if(x=='|') return 1;
if(x=='&') return 2;
return 3;
}

int is_val(char x)
{
if(x=='0'||x=='1')
  return 1;
if(alpha(x)) return 1;
return 0;
}

int val(char x)
{
if(x=='0'||x=='1')
  return (x-'0');
return v[x];
}

int eval()
{
int st[1005],nst=0,i;
for(i=1;pol[i];i++)
  if(is_val(pol[i]))
     st[++nst]=val(pol[i]);
  else
   {
   if(pol[i]=='!')
     st[nst]^=1;
   else
   if(pol[i]=='&')
     st[nst-1]=st[nst-1]&st[nst],nst--;
   else
     st[nst-1]=st[nst-1]|st[nst],nst--;
   }
return st[1];
}


int main()
{
FILE *fin=fopen("bool.in","r"),
     *fout=fopen("bool.out","w");
char ch,s[1005],oper[1005];
int n=0,no=0,i;

ch=fgetc(fin);
while(ch!='\n')
 {
 s[++n]=ch;
 ch=fgetc(fin);
 }
s[n+1]=0;

oper[0]='(';
for(i=1;s[i];i++)
 if(s[i]!=' ')
  {
  if(s[i]=='(')
    oper[++no]='(';
  else
  if(s[i]==')')
    {
    while(oper[no]!='(')
       pol[++np]=oper[no--],oper[no+1]=0;
    no--;
    oper[no+1]=0;
    }
  else
    if(alpha(s[i]))
      if(alpha(s[i+1]))
	{
	switch (s[i])
	  {
	  case 'N': ch='!';i+=2;break;
	  case 'O': ch='|';i++; break;
	  case 'A': ch='&';i+=2;break;
	  case 'T': ch='1';i+=3;break;
	  case 'F': ch='0';i+=4;break;
	  }

	if(ch=='0'||ch=='1')
	  pol[++np]=ch;
	else
	 {
	 while(grad(oper[no])>grad(ch))
	     pol[++np]=oper[no--],oper[no+1]=0;
	 oper[++no]=ch;
	 }
	}
      else
	pol[++np]=s[i];
  }
while(no)
  pol[++np]=oper[no--];
pol[np+1]=0;

for(ch='A';ch<='Z';ch++) v[ch]=0;
fscanf(fin,"%d",&n);
ch=fgetc(fin);
for(i=1;i<=n;i++)
 {
 ch=fgetc(fin);
 v[ch]^=1;
 fprintf(fout,"%d",eval());
 }
fprintf(fout,"\n");
fcloseall();
return 0;
}