Cod sursa(job #2674198)

Utilizator ioana0211Ioana Popa ioana0211 Data 18 noiembrie 2020 19:21:31
Problema Bool Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.2 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;
ifstream fin ("bool.in");
ofstream fout ("bool.out");
char expr[1001], nexpr[1001];
int poz_lit[1000], n, cnt;
void rename ()
{
    char expr_lucru[1001];
    strcpy(expr_lucru, expr);
    int ind=0;
    char *p=strtok(expr_lucru, " ");
    while(p!=NULL)
    {
        int cnt_par=0;
        while(p[cnt_par]=='(') {
            nexpr[++cnt]='(';
            cnt_par++;
        }
        if(strstr(p, "NOT")!=0) nexpr[++cnt]='!';
        else if(strstr(p, "OR")!=0) nexpr[++cnt]='|';
        else if(strstr(p, "AND")!=0) nexpr[++cnt]='&';
        else if(strstr(p, "TRUE")!=0) nexpr[++cnt]='1';
        else if(strstr(p, "FALSE")!=0) nexpr[++cnt]='0';
        else for(int i=0; i<strlen(p); i++){
                if(isalpha(p[i])) {
                    nexpr[++cnt]='0';
                    poz_lit[p[i]-'A']=cnt;
                    break;
                }
            }
        cnt_par=strlen(p)-1;
        while(p[cnt_par]==')'){
           nexpr[++cnt]=')';
            cnt_par--;
        }
        p=strtok(NULL, " ");
    }
}
int cautare (int st, int dr, char s)
{
    int nivel=0;
    for(int i=dr; i>=st; i--)
    {
        if(nexpr[i]==')') nivel++;
        else if(nexpr[i]=='(') nivel--;
        else if(nivel==0 && nexpr[i]==s) return i;
    }
    return -1;
}
bool evaluare (int st, int dr)
{
    int poz=cautare(st, dr, '|');
    if(poz!=-1)
        return evaluare(st, poz-1)|evaluare(poz+1, dr);
    poz=cautare(st, dr, '&');
    if(poz!=-1)
        return evaluare(st, poz-1)&evaluare(poz+1, dr);
    poz=cautare(st, dr, '!');
    if(poz!=-1){
        if(nexpr[poz+1]=='1')
            return 0;
        else return 1;
    }
    if(nexpr[st]=='(') return evaluare(st+1, dr-1);
    if(nexpr[st]=='0') return false;
    else return true;
}
int main()
{
    fin.getline(expr, 1000);
    rename();
    fin>>n;
    char var_modif;
    for(int i=1; i<=n; i++)
    {
        fin>>var_modif;
        int poz=poz_lit[var_modif-'A'];
        if(nexpr[poz]=='0')
            nexpr[poz]='1';
        else nexpr[poz]='0';
        fout<<evaluare(1, cnt);
    }
    return 0;
}