Boolean Logic
Time limit1sMemory limit128 MB
Parse a fully parenthesized proposition formula, then print a truth table with each subformula's value placed at its symbol or operator column.
- Level
Medium6 of 10
- Topics
- Implementation, Recursion, String, Simulation
- Solved
- No attempts yet
Problem
A proposition is a logical formula built from proposition symbols and connective operators. Propositions are defined recursively by the following rules.
- Every proposition symbol (here, a single lower-case letter, for example
aorz) is a proposition. - If is a proposition, then
(!)is a proposition, and is a direct subformula of it. - If and are propositions, then
(&),(|),(-->), and(<->)are propositions, and and are direct subformulas of each of them. - Nothing else is a proposition.
The operators !, &, |, -->, and <-> denote negation, conjunction, disjunction, implication, and equivalence, respectively. A proposition is a subformula of a proposition if , or if is a direct subformula of some proposition and is a subformula of .
Now take a proposition and assign a boolean value ( or ) to every proposition symbol that occurs in . This induces a boolean value for every subformula of according to the standard semantics of the operators:
In this way a value for is obtained. This value depends on the chosen assignment. If contains distinct proposition symbols, there are different assignments. To examine all of them we use a truth table.
A truth table has one line per assignment (that is, lines in total). Each line lists the values of all subformulas under the corresponding assignment. When a subformula is a proposition symbol, its value is aligned with that symbol; otherwise its value is aligned with the center of the operator.
Input
The input contains several test cases, one per line. Each line denotes a proposition and may contain any number of spaces between its characters. The input ends immediately after the newline that follows the last test case.
Output
For each test case, produce a truth table for the given proposition. Begin the truth table by repeating the input line exactly. Then evaluate the proposition and all of its subformulas for every assignment of boolean values to its symbols, and output one line per assignment. Each such line must have the same length as the corresponding input line and may contain only spaces and the characters 0 and 1, with every subformula's value placed in the column described above. Output an empty line after each test case.
Let be the proposition symbols of the given proposition sorted in alphabetical order. Then every assignment that gives to must come before every assignment that gives to . Within each of those blocks, every assignment that gives to must come before every assignment that gives to , and so on (so changes fastest).