Cod sursa(job #516249)

Utilizator rusu_raduRusu Radu rusu_radu Data 23 decembrie 2010 14:48:35
Problema Bool Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.37 kb
#include <cstdio>
#include <cassert>
#include <cstring>
#define Nmax 1005
#define InFile "bool.in"
#define OutFile "bool.out"

using namespace std;

int T[30], poz;
char s[Nmax];

void read();
void work();
void write();
int eval_expr (int &poz);
int eval_termen (int &poz);
int eval_factor (int &poz);

int main()
{
  assert (freopen (InFile, "r", stdin));
  assert (freopen (OutFile, "w", stdout));
  read();
  work();
  write();
  return 0;
}

void read()
{
  gets (s);
}

void work()
{
  int i, nC, n;
  char *p, Cp[Nmax];
  //TRUE
  p=strstr (s, "TRUE");
  while (p!=NULL)
  {
    for (i=0; i<4; i++) *(p+i)=*(p+i)-'A'+'a';
    p=strstr (p, "TRUE");
  }
  //FALSE
  p=strstr (s, "FALSE");
  while (p!=NULL)
  {
    for (i=0; i<5; i++) *(p+i)=*(p+i)-'A'+'a';
    p=strstr (p, "FALSE");
  }
  //NOT
  p=strstr (s, "NOT");
  while (p!=NULL)
  {
    for (i=0; i<3; i++) *(p+i)=*(p+i)-'A'+'a';
    p=strstr (p, "NOT");
  }
  //OR
  p=strstr (s, "OR");
  while (p!=NULL)
  {
    for (i=0; i<2; i++) *(p+i)=*(p+i)-'A'+'a';
    p=strstr (p, "OR");
  }
  //AND
  p=strstr (s, "AND");
  while (p!=NULL)
  {
    for (i=0; i<3; i++) *(p+i)=*(p+i)-'A'+'a';
    p=strstr (p, "AND");
  }
  strcpy (Cp, s);
  nC=strlen (Cp);
  n=0;
  for (i=0 ;i<nC; i++)
    if (Cp[i]!=' ')
      s[n++]=Cp[i];
  s[n]=NULL;
}

void write()
{
  int i, k;
  char c;
  scanf ("%d\n", &k);
  for (i=0; i<k; i++)
  {
    scanf ("%c", &c), T[c-'A']^=1, poz=0;
    printf ("%d", eval_expr(poz));
  }
}

int eval_expr (int &poz)
{
  int t1=eval_termen (poz), t2;
  while (s[poz]=='o')
  {
    poz+=2;
    t2=eval_termen (poz);
    t1=t1|t2;
  }
  return t1;
}

int eval_termen (int &poz)
{
  int f1=eval_factor (poz), f2;
  while (s[poz]=='a')
  {
    poz+=3;
    f2=eval_factor (poz);
    f1=f1&f2;
  }
  return f1;
}

int eval_factor (int &poz)
{
  int nt=1, x;
  while (s[poz]=='n')
  {
    poz+=3;
    nt^=1;
  }
  if (s[poz]=='t')
  {
    poz+=4;
    if (nt)
      return 1;
    else
      return 0;
  }
  if (s[poz]=='f')
  {
    poz+=5;
    if (nt)
      return 0;
    else
      return 1;
  }
  if (s[poz]!='(')
  {
    poz++;
    if (nt)
      return T[s[poz]-'A'];
    else
      return !T[s[poz]-'A'];
  }
  poz++;
  x=eval_expr (poz);
  poz++;
  if (nt)
    return x;
  else
    return !x;
}