ZOJ2483 Boolean Expressions
这道题目是考察数据结构栈的基本应用。
基本思路:开两个栈,一个用来存储操作符,一个用来存储操作数。通过判断语句来检验逻辑符号的优先级。需要注意的是:如果有!运算,一定要先算完。
代码
#include <iostream>
#include <stack>
#include <stdio.h>
#include <string.h>
using namespace std;
char andfun(char m,char n) //首先写三个函数来表示或与非运算
{
if (m == 'V'&&n == 'V')
return 'V';
else
return 'F';
}
char orfun(char m, char n)
{
if (m == 'F'&&n == 'F')
return 'F';
else
return 'V';
}
char notfun(char m)
{
if (m == 'V')
return 'F';
else
return 'V';
}
int main()
{
char expre[110];
int n = 1;
while (gets(expre))
{
stack<char> op;
stack<char> at;
char ans;
//读取的字符串一共有6种情况,每种情况下可能有子情况
for (int i = 0; expre[i]!='\0'; i++)
{
if (expre[i] == ' ')//当是空格的时候
continue;
if (expre[i] == 'V' || expre[i] == 'F')//当是“V”或“F”的时候,压入栈
at.push(expre[i]);
if (expre[i] == '!') //当时“!”的时候,判断下一个字符是否也是“!”,不是的话直接运算
{
if (expre[i + 1] == 'F' || expre[i + 1] == 'V')
{
at.push(notfun(expre[i + 1]));
i++;
}
else
op.push(expre[i]);
}
if (expre[i] == '(') //当是“(”的时候,压入栈
{
op.push(expre[i]);
}
if ((expre[i] == '|')||(expre[i]=='&')) //当是“|”或“&”的时候
{
if (!op.empty())
{
char x;
x = op.top();
if (x == '!')
{
int a;
while (x == '!')//把非算完
{
a = at.top();
at.pop();
at.push(notfun(a));
op.pop();
if (!op.empty())
x = op.top();
if (op.empty())
x = 'f';
}
}
if (x == '|')
{
int a, b;
a = at.top();
at.pop();
b = at.top();
at.pop();
at.push(orfun(a, b));
op.pop();
op.push(expre[i]);
}
if (x == '&')
{
int a, b;
a = at.top();
at.pop();
b = at.top();
at.pop();
at.push(andfun(a, b));
op.pop();
op.push(expre[i]);
}
if (x == '(')
op.push(expre[i]);
}
if (op.empty())
op.push(expre[i]);
}
if (expre[i] == ')'&&!op.empty()) //当是“)”的时候
{
int e;
e = op.top();
while ((e != '(') && !op.empty())
{
char x;
x = op.top();
if (x == '|')
{
int a, b;
a = at.top();
at.pop();
b = at.top();
at.pop();
at.push(orfun(a, b));
}
if (x == '&')
{
int a, b;
a = at.top();
at.pop();
b = at.top();
at.pop();
at.push(andfun(a, b));
}
if (x == '!')
{
int a;
a = at.top();
at.pop();
at.push(notfun(a));
}
op.pop();
e = op.top();
}
op.pop();
}
}
while (!op.empty()) //最后处理剩下的操作符
{
char x;
x = op.top();
if (x == '|')
{
int a, b;
a = at.top();
at.pop();
b = at.top();
at.pop();
at.push(orfun(a, b));
}
if (x == '&')
{
int a, b;
a = at.top();
at.pop();
b = at.top();
at.pop();
at.push(andfun(a, b));
}
if (x == '!')
{
int a;
a = at.top();
at.pop();
at.push(notfun(a));
}
op.pop();
}
ans = at.top();
cout <<"Expression "<<n<<": "<<ans<<endl;
n++;
}
return 0;
}