POJ - 3295 - Tautology = 枚举 + 二叉树遍历

时间:2019-10-22
本文章向大家介绍POJ - 3295 - Tautology = 枚举 + 二叉树遍历,主要包括POJ - 3295 - Tautology = 枚举 + 二叉树遍历使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

http://poj.org/problem?id=3295

题意:给若干个小写字母表示bool变量,大写字母表示bool运算,求这个表达式的是否为永真表达式。

输入形如:

ApNp
ApNq

也就是前缀表达式。

所以就写个东西遍历它构造一棵树,然后给同名变量枚举赋值,假如没有任何赋值使得树根输出0,则为永真表达式。

考察二叉树的递归遍历。

#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;

char s[1005];
int cur;

struct TreeNode {
    char type;
    vector<int> son;
} t[1005];
int top;

//建树
int build(int u) {
    //cout<<"u="<<u<<endl;
    t[u].son.clear();
    if(islower(s[cur])) {
        t[u].type = s[cur];
        ++cur;
        return u;
    } else if(isupper(s[cur])) {
        t[u].type = s[cur];
        ++cur;
        t[u].son.push_back(build(++top));
        if(t[u].type != 'N')
            t[u].son.push_back(build(++top));
        return u;
    }
}

bool calc(int u, int val) {
    //cout<<"u="<<u<<endl;
    //cout<<"t[u].type="<<t[u].type<<endl;
    if(islower(t[u].type)) {
        //cout<<((val >> (t[u].type - 'p')) & 1)<<endl;
        return (val >> (t[u].type - 'p')) & 1;
    } else {
        bool val1 = calc(t[u].son[0], val);
        if(t[u].type == 'N')
            return !val1;
        else {
            bool val2 = calc(t[u].son[1], val);
            if(t[u].type == 'K')
                return val1 & val2;
            if(t[u].type == 'A')
                return val1 | val2;
            if(t[u].type == 'E')
                return val1 == val2;
            if(t[u].type == 'C') {
                if(val1 == 1 && val2 == 0)
                    return 0;
                else
                    return 1;
            }
            exit(-1);
        }
    }
}

int main() {
#ifdef Yinku
    freopen("Yinku.in", "r", stdin);
#endif // Yinku
    while(~scanf("%s", s)) {
        top = cur = 0;
        if(s[0] == '0')
            break;
        build(++top);
        bool all1 = 1;
        for(int i = 0; i < (1 << 5); ++i) {
            if(calc(1, i) == 0) {
                all1 = 0;
                break;
            }
        }
        puts(all1 ? "tautology" : "not");
    }
}

原文地址:https://www.cnblogs.com/Inko/p/11718935.html