Pagini recente » Cod sursa (job #2480852) | Cod sursa (job #1387097) | Cod sursa (job #1452112) | Cod sursa (job #3130319) | Cod sursa (job #2063674)
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <stack>
using namespace std;
ifstream fi("bool.in");
ofstream fo("bool.out");
int n;
string input,schimb;
vector<int> s;
int V[30];
map<string,pair<int,int> > OP;
map<string,int> COD;
void initOP()
{
OP["NOT"]= {3,1},OP["AND"]= {2,1},OP["OR"]= {1,1};
COD["NOT"]=-1,COD["AND"]=-2,COD["OR"]=-3;
}
bool litera(char c)
{
return 'A'<=c&&c<='Z';
}
bool oper(string s)
{
return s=="NOT"||s=="AND"||s=="OR";
}
int truefalse(string s)
{
if(s=="TRUE")
return 1;
if(s=="FALSE")
return 0;
return -1;
}
string fa(string s)
{
string rez,crt;
int t=0;
for(auto c:s)
{
if(litera(c))
crt+=c;
else
{
if(crt!=""&&truefalse(crt)!=-1||crt!=""&&!oper(crt))
{
crt="";
if(t)
rez+=')',t--;
}
else if(crt!=""&&oper(crt))
{
if(crt=="NOT")
rez+='(',t++;
crt="";
}
}
rez+=c;
}
while(t--)
rez+=')';
return rez;
}
vector<int> rpn(string s)
{
string crt;
vector<int> rez;
stack<string> S;
for(auto c:s)
{
if(litera(c))
crt+=c;
else
{
if(crt!=""&&truefalse(crt)!=-1)
{
rez.push_back(truefalse(crt));
crt="";
}
else if(crt!=""&&!oper(crt))
{
rez.push_back(crt[0]-'A'+2);
crt="";
}
else if(crt!=""&&oper(crt))
{
while(!S.empty() && OP[S.top()].first>=OP[crt].first&&OP[S.top()].second==1)
{
rez.push_back(COD[S.top()]);
S.pop();
}
if(S.empty()||crt!="NOT"||crt=="NOT"&&S.top()!="NOT")
S.push(crt);
else
S.pop();
crt="";
}
if(c=='(')
S.push("(");
else if(c==')')
{
while(!S.empty()&&S.top()!="(")
{
rez.push_back(COD[S.top()]);
S.pop();
}
S.pop();
}
}
}
if(crt!=""&&truefalse(crt)!=-1)
{
rez.push_back(truefalse(crt));
crt="";
}
else if(crt!=""&&!oper(crt))
{
rez.push_back(crt[0]-'A'+2);
crt="";
}
while(!S.empty())
{
rez.push_back(COD[S.top()]);
S.pop();
}
return rez;
}
int eval(vector<int> a)
{
stack<int> S;
for(auto i:a)
if(i>=0)
{
int val=i;
if(i>=2)
val=V[i-2];
S.push(val);
}
else if(i==-1&&!S.empty())
{
int val=S.top();
S.pop();
S.push(1-val);
}
else
{
int v1=S.top();
S.pop();
int v2=S.top();
S.pop();
if(i==-2)
S.push(v1&v2);
else
S.push(v1|v2);
}
return S.top();
}
int main()
{
getline(fi,input);
input=fa(input);
fi>>n>>schimb;
initOP();
s=rpn(input);
//fo<<input;
/*
for(auto it:s)
fo<<it<<" ";
*/
for(auto it:schimb)
{
V[it-'A']=1-V[it-'A'];
fo<<eval(s);
}
fi.close();
fo.close();
return 0;
}