一开始不清楚什么思路,觉得怎么才能“智能”的判断是否永真呢?
后来看到只有五个变量,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;
}
}