Using the stack to find the truth value of the expression of logical operation

Source: Internet
Author: User

Today, Zhejiang Polytechnic School Competition D.

After the game was over the Internet to read the article to do it.


Problem D: Logical operation time Limit:1 Sec Memory limit:128 MB
submit:248 solved:36
Description

Do you remember the mode of the University school, let us today and or not into a problem it.

Give you an expression with or not, find the value of the expression, there are eight characters in total.

The three logical operators are ranked by priority as follows.

‘! ': denotes inversion.

' & ': Logic and.

| : Logical OR.

Two characters ' T ', ' F ' indicates true and false, respectively.

There are also left and right brackets, a space of three characters. As with general expressions, parentheses can change precedence.

Input

Each set of data is entered in a row of strings with a string length of less than or equal to 100.

Output

Outputs a number 0 or 1 that represents the answer to a logical expression.

Sample Input
T
Sample Output
1


With 2 stacks, a storage operator, a number that stores operations.

There are three relationships for consecutive operators θ1 and θ2: greater than, equal to, and less than. This allows you to list the priority between "+-*/". As the following table:


     ! & |       (     )      #

!    > &NBSP;&NBSP;&NBSP;&NBSP; >      >&NBSP;&NBSP;&NBSP;&NBSP; <      >      ;

&   < &NBSP;&NBSP;&NBSP;&NBSP; >      > &NBSP;&NBSP;&NBSP;&NBSP; <      > &NBSP;&NBSP;&NBSP;&NBSP;

|    <     <       > &NBSP;&NBSP;&NBSP;&NBSP; <      > &NBSP;&NBSP;&NBSP;&NBSP;

(    < &NBSP;&NBSP;&NBSP;&NBSP; <      < &NBSP;&NBSP;&NBSP;&NBSP; <      =      >

)     > &NBSP;&NBSP;&NBSP;&NBSP; >      > &NBSP;&NBSP;&NBSP;&NBSP; <      > &NBSP;&NBSP;&NBSP;&NBSP;

# < < < < > =


For the sake of simplicity, there is a "#" in the left and right of the expression, and this pair of "#" means that an expression evaluates to completion.

"(" = ")" When a pair of brackets meet, it means that the operation is completed in parentheses.

")" and "(", "#" and "(", "#" and "#" cannot appear consecutively if an expression appears with a syntax error.)

To implement the first algorithm, two working stacks can be used, one is Q, a register operator, and the other is P, which is used to register the operand and the result of the operation.



The basic idea of the algorithm.

First, the operand stack is an empty stack, and the expression starting with "#" is the bottom element of the stack.

Each character in the expression is read sequentially, if the operand is in the Q stack, if the operator and the stack top operator of the Q stack compare precedence, until the entire expression is evaluated (the top element of the Q stack and the characters currently being read in are "#")

Code implementation:

<pre name= "code" class= "CPP" ><span style= "FONT-SIZE:14PX;" > #include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include < string> #include <algorithm> #include <queue> #include <stack>using namespace Std;const Double PI = ACOs ( -1.0); const double e = 2.718281828459;const double eps = 1e-8;const int maxn = 110;char S[maxn];char opset[6] = {'! ' , ' & ', ' | ', ' (', ') ', ' # '};char prio[6][6] ={    ' > ', ' > ', ' > ', ' < ', ' > ', ' > ',  & nbsp;  ' < ', ' > ', ' > ', ' < ', ' > ', ' > ',    ' < ', ' < ', ' > ', ' < ', ' > ', ' ; ',    ' < ', ' < ', ' < ', ' < ', ' = ', ' > ',    ' > ', ' > ', ' > ', ' < ', ' ; ', ' > ',    ' < ', ' < ', ' < ', ' < ', ' > ', ' = ',};//find the corresponding operator in the opset array subscript int FindIndex (char op) {     for (int i = 0; i < 6; i++)     {        if (opset[i] = = op)             return i;    }}//comparing the precedence of the operator in the top element of the Q stack with the current s[i] Char compare (char A, char b) {    int x = FindIndex (a);     int y = FindIndex (b);    return prio[x][y];} Computes the result of X y under the OP operator int calc (int x, int y, char op) {    if (op = = ' | ')         return x|y;    if (op = = ' & ')          return x&y;    return 0;} int main () {   //freopen ("In.txt", "R", stdin);   //freopen ("OUT.txt", "w", stdout);     while (scanf ("%s", s)! = EOF)     {        int LENS = strlen (s);        s[lens] = ' # ';  //s array tail saved as ' # '          s[lens+1] = ';        int t, x, y;        char op;        int i = 0;         stack<int>p; //For storing operands, integer elements         stack<char>q; //For storing operation symbols, character elements         Q.push (' # '); //Save Stack as ' # '         while (s[i]!= ' # ' | | Q.top ()! = ' # ')         {            //When the S array is read to the end, and Q has been read to the bottom of the stack, it shows the end of all operations             if (s [i]== ' T ' | | s[i]== ' F ')             {                //Read to T or F, convert to 0 or 1 into stacks                  if (s[i] = = ' T ')                      T = 1;                 else                     T = 0;                 P.push (t);                 i++;           }             else if (s[i]! = ")              {                //Because the input string contains spaces, the spaces are slightly over                  switch (compare (Q.top (), s[i))                  {                 Case ' < ': //stack top element has low priority, the current element is in the stack                      Q.push (s[i]);                     i++;                     break;                 case ' = '://Left and right brackets match, brackets and receives next character                      Q.pop ();                      i++;                     Break;                case ' > ':  Back up the stack and put the results of the operation into the stack                      if (q.top () = = '! ')                      {  //stack top element is! , single-Mesh operator                          x = p.top ();                         P.pop ();                          P.push (!x);                         Q.pop ();                     }                     else                     {  //stack top element not!                          x = p.top ();                         P.pop ();                         y = P.top ();                         P.pop ();                        op = Q.top ();                         Q.pop ();   //calculation results are incorporated into the stack                          P.push (Calc (x, Y, op));                    }                     break;                }           }        }        int ans = p.top ();       &nbSp cout<<ans<<endl;   }    return 0;} </span>



Using the stack to find the truth value of the expression of logical operation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.