POJ3295 Tautology

一开始不清楚什么思路,觉得怎么才能“智能”的判断是否永真呢?
后来看到只有五个变量,1和0可以2^5暴力来做。
接下来就是计算表达式的值了,可以用一个stack记录操作符和操作数。计算的时候从右向左入栈,栈里面存的都是计算出来的值,遇到操作符时开始取栈里的数值计算。http://blog.csdn.net/lyy289065406/article/details/6642766
也可以用递归,更简洁。http://blog.csdn.net/allenlsy/article/details/4885948

还有做POJ的时候,适当还是可以debug的。

#include<iostream>
#include<string>
#include<stack>  
using namespace std;

int p, q, r, s, t;
stack<int> st;
string str;

bool variable(char c)
{
    switch (c)
    {
        case('p'):
            st.push(p); return true;
        case('q'):
            st.push(q); return true;
        case('r'):
            st.push(r); return true;
        case('s'):
            st.push(s); return true;
        case('t'):
            st.push(t); return true;
        default:
            return false;
    }
}

void operate(char c)
{
    int x, y;
    switch(c)
    {
        case('N'):
            x = st.top();
            st.pop();
            st.push(!x);
            break;
        case('K'):
            x = st.top();
            st.pop();
            y = st.top();
            st.pop();
            st.push(x && y);
            break;
        case('A'):
            x = st.top();
            st.pop();
            y = st.top();
            st.pop();
            st.push(x || y);
            break;
        case('C'):
            x = st.top();
            st.pop();
            y = st.top();
            st.pop();
            st.push((!x) || y);
            break;
        case('E'):
            x = st.top();
            st.pop();
            y = st.top();
            st.pop();
            st.push(x == y);
            break;
    }
}

int calc()
{
    int len = str.length();
    for (int i = len - 1; i >= 0; i--)
    {
        if (!variable(str[i]))
            operate(str[i]);
    }
    int ans = st.top();
    st.pop();
    return ans;
}

int main(void)
{
    while (cin >> str && str!="0")  
    {
		bool tautology = true;
        for (p = 0; p <= 1 && tautology; p++)
            for (q = 0; q <= 1 && tautology; q++)
                for (r = 0; r <= 1 && tautology; r++)
                    for (s = 0; s <= 1 && tautology; s++)
                        for (t = 0; t <=1 && tautology; t++)
                        {
                            if (calc() != 1)
                                tautology = false;
                        }
		if (!tautology)  
			cout << "not" << endl;  
		else  
			cout << "tautology" << endl;
    }
}

  

转载于:https://www.cnblogs.com/lautsie/p/3361054.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值