原题链接:http://poj.org/problem?id=2106

题意:或、与、 非的多元表达式的求值;

思路:中缀表达式变为后缀表达式;

代码:

  1 #include<cstdio>
  2 #include<iostream>
  3 #include<stack>
  4 #include<string>
  5 
  6 using namespace std;
  7 
  8 struct Pri{
  9     char op;
 10     int pri;
 11 }lpri[5]={{'(',1},{'|',3},{'&',5},{'!',6},{')',8}},
 12  rpri[5]={{'(',8},{'|',2},{'&',4},{'!',7},{')',1}};
 13  
 14  int find_left(char op)
 15  {
 16      for(int i=0;i<5;i++)
 17          if(lpri[i].op==op)
 18              return lpri[i].pri;
 19  }
 20  
 21  int find_right(char op)
 22  {
 23      for(int i=0;i<5;i++)
 24          if(rpri[i].op==op)
 25              return rpri[i].pri;
 26  }
 27  
 28 int Precede(char op1,char op2)
 29 {
 30     int L=find_left(op1);
 31     int R=find_right(op2);
 32     if(L==R)    
 33         return 0;
 34     if(L>R)
 35         return 1;
 36     return -1;     
 37 } 
 38 
 39 int Run(stack<int>& num,char op)
 40 {
 41     int a=num.top();
 42     num.pop();
 43     
 44     if(op=='!')
 45         return !a;
 46     int b=num.top();
 47     num.pop();
 48     switch(op)
 49     {
 50         case '|':
 51             return a||b;
 52         case '&':
 53             return a&&b;
 54     }
 55 }
 56 
 57 int main()
 58 {
 59     string s;
 60     int ca=1;
 61     while(getline(cin,s))
 62     {
 63         int i;
 64         stack<int> num;
 65         stack<char> op;
 66          for(i=0;i<s.length();i++)
 67         {
 68             if(s[i]==' ')
 69                 continue;    
 70             else if(s[i]=='V')
 71                 num.push(1);    
 72             else if(s[i]=='F')
 73                 num.push(0);
 74             else
 75             {
 76                 if(op.empty())
 77                 {
 78                     op.push(s[i]);    
 79                 }
 80                 else
 81                 {
 82                     int judg=Precede(op.top(),s[i]);
 83                     int t;
 84                     switch(judg)
 85                     {
 86                         case 0:
 87                             op.pop();break;
 88                         case 1:
 89                             t=Run(num,op.top());
 90                             num.push(t);
 91                             op.pop();
 92                             i--;break;
 93                         case -1:
 94                             op.push(s[i]);break;
 95                     }
 96                 }
 97             }
 98         }
 99         while(!op.empty())
100         {
101             num.push(Run(num,op.top()));
102                 op.pop();
103         }
104         if(num.top()==1)
105             printf("Expression %d: V\n",ca++);
106         else
107             printf("Expression %d: F\n",ca++);
108     }
109     
110     return 0;
111 }

注意:特殊数据:!!!!!!!!!!!!!!!F

ac与RE只在一念只差

-------------------------------------------欢迎评论提问-------------------------------------------