Pagini recente » Cod sursa (job #704785) | Cod sursa (job #33853) | Rating SuntUnNanoTub (vlad2004) | Cod sursa (job #641017) | Cod sursa (job #1424972)
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <stack>
#include <unordered_map>
using namespace std;
void lex(const string& from, string& to, unordered_map<char, bool>& dict){
auto it = begin(from);
while(it != end(from)){
if(*it == 'A' && *(it+1) == 'N'){
to.push_back('&');
it += 3; }
else if(*it == 'O' && *(it+1) == 'R'){
to.push_back('|');
it += 2; }
else if(*it == 'N' && *(it+1) == 'O'){
to.push_back('!');
it += 3; }
else if(*it == 'T' && *(it+1) == 'R'){
to.push_back('t');
it += 4; }
else if(*it == 'F' && *(it+1) == 'A'){
to.push_back('f');
it += 5; }
else if(*it == '('){
to.push_back('(');
++it; }
else if(*it == ')'){
to.push_back(')');
++it; }
else{
to.push_back(*it);
dict[*it] = false;
++it; }
while(isspace(*it)){
++it; } } }
constexpr int precedence(const char c){
return (c == '(') ? -1 : (c == '|') ? 0 : (c == '&') ? 1 : (c == '!') ? 2 : 3; }
void parse(const string& from, string& to){
stack<char> st;
for(auto x : from){
if(x == '('){
st.push('('); }
else if(x == ')'){
while((!st.empty()) && st.top() != '('){
to.push_back(st.top());
st.pop(); }
st.pop(); }
else if(isalpha(x)){
to.push_back(x); }
else{
const int prec = precedence(x);
while((!st.empty()) && precedence(st.top()) > prec){
to.push_back(st.top());
st.pop(); }
st.push(x); } }
while(!st.empty()){
to.push_back(st.top());
st.pop(); } }
bool eval(string::reverse_iterator& loc, unordered_map<char, bool>& dict){
const auto tmp = loc;
bool first, second;
char c;
switch(c = *(loc++)){
case '!':
first = eval(loc, dict);
return !first;
case '&':
first = eval(loc, dict);
second = eval(loc, dict);
return first && second;
case '|':
first = eval(loc, dict);
second = eval(loc, dict);
return first || second;
case 't':
return true;
case 'f':
return false;
default:
return dict[c]; } }
int main(){
ifstream f("bool.in");
ofstream g("bool.out");
string brut, lexat, parsat;
unordered_map<char, bool> dict;
getline(f, brut);
lex(brut, lexat, dict);
parse(lexat, parsat);
int n = 0;
f >> n >> ws;
string s(n, 0);
f.read(&s[0], n);
for(int i = 0; i < n; ++i){
dict[s[i]] = !dict[s[i]];
auto it = parsat.rbegin();
const auto x = eval(it, dict);
g << x; }
return 0; }