Boolean Expressions

来源:互联网 发布:京东java笔试题 编辑:程序博客网 时间:2024/05/17 07:28

 Boolean Expressions

时间限制: 1 Sec  内存限制: 128 MB
提交: 4  解决: 4
[提交][状态][讨论版]

题目描述

The objective of the program you are going to produce is to evaluate boolean expressions as the one shown next: 
Expression: ( V | V ) & F & ( F | V )
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. 

输入

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. 

输出

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. 

样例输入

( V | V ) & F & ( F| V)!V | V & V & !F & (F | V ) & (!F | F | !V & V)(F&F|V|!V&!F&!(F|F&V))

样例输出

Expression 1: FExpression 2: VExpression 3: V
#include<stdio.h>#include<stack>#include<iostream>using namespace std;char a[101],b[101],c1,k,k1;stack<char>s1;void f(){int j;for(j=k-1;j>=0;j--){if(a[j]=='!'){if(a[j-1]=='F')b[k1++]='V';if(a[j-1]=='V')b[k1++]='F';j--;}elseb[k1++]=a[j];}c1=b[0];for(j=1;j<k1;j=j+2){if(b[j]=='|'){if(c1=='F'&&b[j+1]=='F')c1='F';elsec1='V';}if(b[j]=='&'){if(c1=='V'&&b[j+1]=='V')c1='V';elsec1='F';}}}int main(){string s;int t=0,i,j;while(getline(cin,s)){t++;for(i=0;i<s.size();i++){if(s[i]!=' '&&s[i]!=')')s1.push(s[i]);if(s[i]==')'){       k=0;k1=0;   while(s1.top()!='('){   a[k++]=s1.top();   s1.pop();}s1.pop();f();s1.push(c1);}}k=0,k1=0;while(!s1.empty()){a[k++]=s1.top();s1.pop();    }    f();printf("Expression %d: %c\n",t,c1);}}