Cod sursa(job #500740)

Utilizator FERI24Forrai Francisc FERI24 Data 12 noiembrie 2010 22:48:40
Problema Bool Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.3 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
#include <algorithm>
#include <cassert>
using namespace std;

int n,val[28];
string exp;

int pr(char op) {
    if('~'==op) return 3;
    if('&'==op) return 2;
    if('|'==op) return 1;
    if('('==op) return 0;
    assert(1);
}

stack<char> out,ops;

void shuntingYard() {
    int sz=exp.size();
    for(int i=0; i<sz; ++i) {
        if(exp[i]==' ') continue;
        else if('T'==exp[i] && 'R'==exp[i+1] && 'U'==exp[i+2] && 'E'==exp[i+3]) out.push(char(91)),i+=3;
        else if('F'==exp[i] && 'A'==exp[i+1] && 'L'==exp[i+2] && 'S'==exp[i+3] && 'E'==exp[i+4]) out.push(char(92)),i+=4;
        else if('N'==exp[i] && 'O'==exp[i+1] && 'T'==exp[i+2]) ops.push('~'),i+=2;
        else if('A'==exp[i] && 'N'==exp[i+1] && 'D'==exp[i+2]) {
            for(;ops.size() && pr('&')<pr(ops.top());out.push(ops.top()),ops.pop());
            ops.push('&');
            i+=2;
        }
        else if('O'==exp[i] && 'R'==exp[i+1]) {
            for(;ops.size() && pr('|')<pr(ops.top());out.push(ops.top()),ops.pop());
            ops.push('|');
            ++i;
        }
        else if('('==exp[i]) ops.push('(');
        else if(')'==exp[i]) {
            for(;'('!=ops.top();out.push(ops.top()),ops.pop());
            ops.pop();
        }
        else out.push(exp[i]);
    }
    for(;ops.size(); out.push(ops.top()),ops.pop());
    for(;out.size();ops.push(out.top()),out.pop());
}

int evalPol(stack<char> a) {
    int rez[1024], lgRez=0;
    for(;a.size(); a.pop())
        switch (a.top()) {
            case '~':
                rez[lgRez-1]^=1;
                break;
            case '&':
                rez[lgRez-2]=rez[lgRez-2]&rez[lgRez-1];
                --lgRez;
                break;
            case '|':
                rez[lgRez-2]=rez[lgRez-2]|rez[lgRez-1];
                --lgRez;
                break;
            default:
                rez[lgRez++]=val[a.top()-'A'];
        }
    return rez[0];
}

int main()
{
	ifstream f("bool.in");
	ofstream g("bool.out");
	getline(f,exp);
	val[26]=1;
	shuntingYard();
	f>>n;
	char c;
	if(n)
	for(int i=1; i<=n; ++i) {
	    f>>c;
	    val[c-'A']^=1;
	    g<<evalPol(ops);
	}
	else g<<evalPol(ops);
	f.close();
	g.close();
	return 0;
}