Pagini recente » Cod sursa (job #1429331) | Cod sursa (job #1576980) | Cod sursa (job #946575) | Cod sursa (job #2311817) | Cod sursa (job #2634387)
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>
#include <map>
#include <string.h>
#define MAX_LEN 1001
#define NMAX 100
using namespace std;
ifstream fin("bool.in");
ofstream fout("bool.out");
struct elts {
int val, type;
};
char expr[MAX_LEN];
int n;
vector<elts> vec;
map<char, bool> var;
map<char, int> priority;
char getVar(int& i) {
if (expr[i] >= 'A' && expr[i] <= 'Z' && (expr[i + 1] == '\0' || expr[i + 1] == ' ' || expr[i+1]==')' || expr[i + 1] == '('))
return expr[i];
char op[10];
int k=0;
int j = i;
while (expr[i] >= 'A' && expr[i] <= 'Z')
op[k++] = expr[i++];
op[k] = '\0';
--i;
if (strcmp(op, "TRUE")==0) return '1';
if (strcmp(op, "FALSE") == 0) return '0';
i = j;
return 0;
}
char getOperator(int& i) {
char op[10];
int k = 0;
int j = i;
while (expr[i] >= 'A' && expr[i] <= 'Z')
op[k++] = expr[i++];
op[k] = '\0';
--i;
if (strcmp(op, "AND") == 0)return '&';
if (strcmp(op, "OR") == 0) return '|';
if (strcmp(op, "NOT") == 0) return '~';
i = j;
return 0;
}
void buildPostfix() {
stack<char> op;
for (int i = 0;expr[i] != '\0';++i) {
if (expr[i] == ' ') {
continue;
}
char c;
c = getVar(i);
if (c != 0) { var[c] = false;vec.push_back(elts{ c,0 }); continue; }
c = getOperator(i);
if (c != 0) {
while (!op.empty() && op.top() != '(' && priority[op.top()] >= priority[c]) {
vec.push_back(elts{ op.top(),1 });
op.pop();
}
op.push(c);
continue;
}
if (expr[i] == '(') { op.push('('); continue; }
if (expr[i] == ')') {
while (op.top() != '(') {
vec.push_back(elts{ op.top(),1 });
op.pop();
}
op.pop();
}
}
while (!op.empty()) {
vec.push_back(elts{ op.top(),1 });
op.pop();
}
}
bool getRes(bool a, bool b, char op) {
if (op == '~')
return (!a);
if (op == '&')
return (a && b);
if (op == '|')
return (a || b);
return 1 / 0;
}
bool compute() {
stack<bool> val;
for (int i = 0;i < vec.size();++i) {
cout << vec[i].type << ' ' << (char)vec[i].val << '\n';
if (vec[i].type == 0)
val.push(var[vec[i].val]);
else {
bool a=false, b=false;
if (vec[i].val == '~') {
b = val.top();
val.pop();
}
else {
a = val.top();val.pop();
b = val.top();val.pop();
}
val.push(getRes(b, a, vec[i].val));
}
}
return val.top();
}
int main()
{
priority['&'] = 2;
priority['|'] = 1;
priority['~'] = 3;
fin.getline(expr, MAX_LEN);
buildPostfix();
var['0'] = false;
var['1'] = true;
fin >> n;
while (n--) {
char c;
fin >> c;
var[c] = !var[c];
bool res = compute();
if (res == true)fout << "1";
else fout << "0";
}
return 0;
}