Boolean Expressions
Description
The objective of the program you are going to produce is to evaluate boolean expressions as the one shown next:
where V is for True, and F is for False. The expressions may include the following operators: ! for not , & for and, | for or , the use of parenthesis for operations grouping is also allowed. To perform the evaluation of an expression, it will be considered the priority of the operators, the not having the highest, and the or the lowest. The program must yield V or F , as the result for each expression in the input file. Input
The expressions are of a variable length, although will never exceed 100 symbols. Symbols may be separated by any number of spaces or no spaces at all, therefore, the total length of an expression, as a number of characters, is unknown.
The number of expressions in the input file is variable and will never be greater than 20. Each expression is presented in a new line, as shown below. Output
For each test expression, print "Expression " followed by its sequence number, ": ", and the resulting value of the corresponding test expression. Separate the output for consecutive test expressions with a new line.
Use the same format as that shown in the sample output shown below. Sample Input ( V | V ) & F & ( F| V) !V | V & V & !F & (F | V ) & (!F | F | !V & V) (F&F|V|!V&!F&!(F|F&V)) Sample Output Expression 1: F Expression 2: V Expression 3: V Source |
[Submit] [Go Back] [Status] [Discuss]
就是简单的表达式求值,一直RE在了:只有当栈顶运算符的比较级大于将入栈运算符的比较级是才将栈顶的运算符入ans[]数组中!
代码:
#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>
using namespace std;
char s[1000010],ans[1000005];
int cmp(char c)
{
if(c=='(') return 0;
else if(c=='|') return 1;
else if(c=='&') return 2;
else if(c=='!') return 3;
}
int main()
{
stack<char>oc;//操作符栈;
stack<int >on;//操作数栈;
int cal=0;
while(gets(s))
{
char ch;
int i=0;
cal++;
while(!oc.empty()) oc.pop();
while(!on.empty()) on.pop();
int len=strlen(s);
s[len]='=';
int k=0;
for(int i=0; i<=len; i++)
{
if(s[i]=='V'||s[i]=='F')
ans[k++]=s[i];
else if(s[i]=='!'||s[i]=='&'||s[i]=='|')
{
if(oc.empty())
oc.push(s[i]);
else
{
while(!oc.empty()&&cmp(oc.top())>cmp(s[i]))
{
ans[k++]=oc.top();
oc.pop();
}
oc.push(s[i]);
}
}
else if(s[i]==' ')
continue;
else if(s[i]=='(')
{
oc.push(s[i]);
}
else if(s[i]==')')
{
while(oc.top()!='(')
{
ans[k++]=oc.top();
oc.pop();
}
oc.pop();
}
else if(s[i]=='=')
{
while(!oc.empty())
{
ans[k++]=oc.top();
oc.pop();
}
}
}
for(int i=0; i<k; i++)
{
if(ans[i]=='V') on.push(1);
else if(ans[i]=='F') on.push(0);
else if(ans[i]=='!')
{
int x=on.top();
on.pop();
on.push(!x);
}
else if(ans[i]=='&'||ans[i]=='|')
{
int x=on.top();
on.pop();
int y=on.top();
on.pop();
if(ans[i]=='&') on.push(x&y);
else on.push(x|y);
}
}
printf("Expression %d: ",cal);
if(on.top())
printf("V\n");
else
printf("F\n");
}
return 0;
}