Pagini recente » Istoria paginii runda/000000/clasament | Cod sursa (job #726058) | Cod sursa (job #1462676) | Cod sursa (job #205877) | Cod sursa (job #361041)
Cod sursa(job #361041)
#include <stack>
#include <string>
#include <fstream>
#include <cstdlib>
#include <algorithm>
#define InFile "bool.in"
#define OutFile "bool.out"
/*
*
*/
using namespace std;
ifstream in;
ofstream out;
bool v[30];
inline int priority( char x )
{
if( '(' == x )
return 0;
if( '|' == x )
return 1;
if( '&' == x )
return 2;
if( '!' == x )
return 3;
if( ')' == x )
return 4;
return -1;
}
inline bool is_letter( char x )
{
return x >= 'A' && x <= 'Z';
}
string transform( string* expresion )
{int p;
char opp;
stack<char> s;
string t, op;
string::const_iterator it=expresion->begin(), iend=expresion->end();
while( it < iend )
{
if( is_letter(*it) )
{
if( it+1 < iend && is_letter(*(it+1)) ) //if it is an operator
{op.clear();
while( it < iend && is_letter(*it) )
op.push_back(*it), ++it;
if( "OR" == op )
opp='|';
else if( "AND" == op )
opp='&';
else if( "NOT" == op )
opp='!';
else if( "TRUE" == op )
{
t.push_back('t');
continue;
}
else if( "FALSE" == op )
{
t.push_back('f');
continue;
}
p=priority(opp);
while( !s.empty() && p <= priority(s.top()) )
t.push_back(s.top()), s.pop();
s.push(opp);
continue;
}
t.push_back(*it);
++it;
continue;
}
if( '(' == *it )
{
s.push('('); ++it;
continue;
}
if( ')' == *it )
{++it;
while( !s.empty() && '(' != s.top() )
t.push_back(s.top()), s.pop();
if( !s.empty() )
s.pop();
continue;
}
++it;
}
while( !s.empty() )
t.push_back(s.top()), s.pop();
return t;
}
bool evaluate( string* expresion )
{bool a, b;
stack<bool> s;
string::const_iterator it=expresion->begin(), iend=expresion->end();
while( it < iend )
{
if( 'f' == *it )
{++it;
s.push(false);
continue;
}
if( 't' == *it )
{++it;
s.push(true);
continue;
}
if( is_letter(*it) )
{
s.push(v[*it-'A']); ++it;
continue;
}
if( '!' == *it )
{++it;
a=s.top(); s.pop();
s.push(!a);
continue;
}
b=s.top(), s.pop();
a=s.top(), s.pop();
switch( *it )
{
case '|' : s.push(a|b); break;
case '&' : s.push(a&b); break;
}
++it;
}
return s.top();
}
int main()
{char ch;
int n;
string expresion;
in.open(InFile);
getline( in, expresion );
in>>n;
expresion=transform(&expresion);
out.open(OutFile);
while( n-- )
{
in>>ch;
v[ch-'A']=!v[ch-'A'];
out<<evaluate(&expresion);
}
return 0;
}