Загрузка данных
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Node {
char data;
Node* next;
};
void push(Node*& top, char x) {
Node* p = new Node;
p->data = x;
p->next = top;
top = p;
}
char pop(Node*& top) {
char x = top->data;
Node* p = top;
top = top->next;
delete p;
return x;
}
char peek(Node* top) {
return top->data;
}
int priority(char op) {
if (op == '!') return 3;
if (op == '&') return 2;
if (op == '|') return 1;
return 0;
}
void calc(Node*& values, Node*& ops) {
char op = pop(ops);
// отрицание
if (op == '!') {
char a = pop(values);
if (a == '1')
push(values, '0');
else
push(values, '1');
}
// И / ИЛИ
else {
char b = pop(values);
char a = pop(values);
bool x = (a == '1');
bool y = (b == '1');
if (op == '&')
push(values, (x && y) ? '1' : '0');
else
push(values, (x || y) ? '1' : '0');
}
}
int main() {
ifstream file("LOG.txt");
string s;
getline(file, s);
// заменяем символы из задания на обычные
size_t pos;
while ((pos = s.find("¬")) != string::npos)
s.replace(pos, string("¬").size(), "!");
while ((pos = s.find("∧")) != string::npos)
s.replace(pos, string("∧").size(), "&");
while ((pos = s.find("∨")) != string::npos)
s.replace(pos, string("∨").size(), "|");
Node* values = nullptr; // стек значений
Node* ops = nullptr; // стек операций
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == ' ')
continue;
// true
if (s.compare(i, 4, "true") == 0) {
push(values, '1');
i += 3;
while (ops != nullptr && peek(ops) == '!')
calc(values, ops);
}
// false
else if (s.compare(i, 5, "false") == 0) {
push(values, '0');
i += 4;
while (ops != nullptr && peek(ops) == '!')
calc(values, ops);
}
// короткая запись t / f
else if (s[i] == 't' || s[i] == 'f') {
if (s[i] == 't')
push(values, '1');
else
push(values, '0');
while (ops != nullptr && peek(ops) == '!')
calc(values, ops);
}
// открывающая скобка
else if (s[i] == '(') {
push(ops, '(');
}
// отрицание
else if (s[i] == '!') {
push(ops, '!');
}
// И или ИЛИ
else if (s[i] == '&' || s[i] == '|') {
while (ops != nullptr &&
peek(ops) != '(' &&
priority(peek(ops)) >= priority(s[i])) {
calc(values, ops);
}
push(ops, s[i]);
}
// закрывающая скобка
else if (s[i] == ')') {
while (ops != nullptr && peek(ops) != '(')
calc(values, ops);
// удалить (
if (ops != nullptr)
pop(ops);
// если перед скобками было отрицание
while (ops != nullptr && peek(ops) == '!')
calc(values, ops);
}
}
while (ops != nullptr)
calc(values, ops);
if (peek(values) == '1')
cout << true;
else
cout << false;
while (values != nullptr)
pop(values);
return 0;
}