Cod sursa(job #2877380)

Utilizator ezluciPirtac Eduard ezluci Data 24 martie 2022 18:09:07
Problema Bool Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2 kb
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
ifstream fin ("bool.in");
ofstream fout ("bool.out");

string s;   int p;
bool variab[26];

bool termen();
bool termenOr();
bool eval();
void replace(string &s, string &what, string &with);


bool termen()
{
   bool ans;
   bool negatie = 0;
   while (s[p] == '~')
   {
      negatie = ~negatie;
      p++;
   }
   
   if (s[p] == '(')
   {
      p++;
      ans = eval();
      p++;
   }
   else if (isalpha(s[p]))
   {
      ans = variab[s[p] - 'A'];
      p++;
   }
   else if (isdigit(s[p]))
   {
      ans = s[p] - '0';
      p++;
   }
   
   if (negatie)
      return ~ans;
   else
      return ans;
}


bool termenOr()
{
   bool ans = termen();
   bool t;

   while (s[p] == '&')
   {
      p++;
      t = termen();
      ans &= t;
   }

   return ans;
}


bool eval()
{
   bool ans = termenOr();
   bool t;

   while (s[p] == '|')
   {
      p++;
      t = termenOr();
      ans |= t;
   }

   return ans;
}


void replace(string &s, string &what, string &with)
{
   int i, j;
   bool ok;

   for (i = 0; i <= s.size() - what.size(); ++i)
   {
      ok = true;
      for (j = 0; j < what.size(); ++j)
         if (s[i+j] != what[j])
            ok = false;
            
      if (ok)
         s.replace(s.begin() + i, s.begin() + i + what.size(), with.c_str());
   }
}


int main()
{
   getline(fin, s);
   string what, with;
   what = " AND ";
   with = "&";
   replace(s, what, with);
   
   what = " OR ";
   with = "|";
   replace(s, what, with);
   
   what = "NOT ";
   with = "~";
   replace(s, what, with);
   
   what = "TRUE";
   with = "1";
   replace(s, what, with);

   what = "FALSE";
   with = "0";
   replace(s, what, with);

   int n;   char c;
   fin >> n;
   while (n--)
   {
      fin >> c;
      variab[c - 'A'] = !variab[c - 'A'];
      p = 0;
      fout << eval();
   }

   return 0;
}