Time limit:1000ms
Memory limit:30000k
Description
The objective of the program your are going to produce are to evaluate Boolean expressions as the one shown next:
Expression: (V | V) & F & (F | V
Where V is to True, and F is for False. The expressions may include the following operators:! For isn't, & for and, | For or, the use of parenthesis for operations grouping is also allowed.
To perform the evaluation of a expression, it'll be considered the priority of the operators, the not has the highes T, and the lowest. The program must yield V or F, as the result of each of the expression in the input file.
Input
The expressions are of a variable length, although to never exceed. Symbols May is separated by any number of spaces or no spaces at all, therefore, the total length of a expression, as a n Umber of characters, is unknown.
The number of expressions in the input file is variable and would never be greater than 20. Each expression are 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 Corres ponding test expression. Separate the output for consecutive test expressions with a new line.
Use the same format as this 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
México and America 2004
Open two stacks and determine the good operator precedence. (see Code for details)
Complete code:
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
/*0ms,388kb*/#include <cstdio> const int MAXN = 110;
BOOL VAL[MAXN];
int OP[MAXN], VP, pp;
void Insert (bool b) {while (pp && op[pp-1] = = 3) {b =!b;
--PP;
} val[vp++] = b;
void Calc () {bool b = VAL[--VP];
BOOL a = VAL[--VP];
int OPR = op[--pp];
Insert (OPR = 1? A | b:a & B); /* Define priority as (higher number priority) (: 0 |
: 1 &:2!:3): 4/int main () {int cas = 0;
char c;
while (~ (c = GetChar ())) {VP = PP = 0;
do {if (c = = ') op[pp++] = 0; else if (c = =) ') {while (pp && op[pp-1])///handles all operations in parentheses C
ALC ();
--PP;
Insert (VAL[--VP])///count '! '
else if (c = = '! ')
op[pp++] = 3;
else if (c = = ' & ') {while (pp && op[pp-1] >= 2)///' & '! '
Calc ();
op[pp++] = 2;
else if (c = = ' | ') {while (pp && op[pp-1] >= 1)///' | '
' & '! '
Calc ();
op[pp++] = 1;
else if (c = = ' V ' | | c = = ' F ') insert (c = = ' V '? true:false);
The space is ignored} while ((c = GetChar ())!= && ~c);
while (PP) calc (); printf ("Expression%d:%c\n", ++cas, (val[0)?
' V ': ' F '); }
}