构造法

poj3295

题目不难,就是题意有点难理解(英语不好啊...)

 

题目的意思是一个式子只有pqrst和KANCE组成(一开始理解成小写字母都是变量了,不知道该如何枚举了),然后判断式子是否是永真式

用栈来进行计算,遇到变量入栈,遇到操作符取出栈中元素,运算结果再入栈,最后栈中剩余的结果就是最终计算的结果。

 

#include <iostream>
#include <cstdio>
#include <stack>
#include <cstring>

using namespace std;



stack<int> s;
int pp,qq,rr,ss,tt;

bool isvalue(char a)
{
     switch(a)
    {
        case 'p':s.push(pp);return true;
        case 'q':s.push(qq);return true;
        case 'r':s.push(rr);return true;
        case 's':s.push(ss);return true;
        case 't':s.push(tt);return true;
    }
    return false;
}



void operators(char op)
{
    switch(op)
    {
        case 'K':
            {
                int x=s.top();
                s.pop();
                int y=s.top();
                s.pop();
                s.push(x&&y);
                break;
            }
        case 'A':
            {
                int x=s.top();
                s.pop();
                int y=s.top();
                s.pop();
                s.push(x||y);
                break;
            }
        case 'C':
            {
                int x=s.top();
                s.pop();
                int y=s.top();
                s.pop();
                s.push((!x)||y);
                break;
            }
        case 'E':
            {
                int x=s.top();
                s.pop();
                int y=s.top();
                s.pop();
                s.push(x==y);
                break;
            }
        case 'N':
            {
                int x=s.top();
                s.pop();
                s.push(!x);
                x=s.top();
                //printf("re:%d\n",x);
                break;
            }
    }
    return;
}



int main()
{
   char a[110];
   while(cin>>a&&a[0]!='0')
   {
       int len = strlen(a);
       bool flag=1;
       for(pp=0;pp<=1;pp++)
       {
           for(qq=0;qq<=1;qq++)
           {
               for(rr=0;rr<=1;rr++)
               {
                   for(ss=0;ss<=1;ss++)
                   {
                       for(tt=0;tt<=1;tt++)
                       {
                           for(int i=len-1;i>=0;i--)
                           {
                               if(!isvalue(a[i]))
                                  operators(a[i]);
                           }
                           flag=s.top();
                           s.pop();
                           if(!flag) break;
                       }
                       if(!flag) break;
                   }
                   if(!flag) break;
               }
               if(!flag) break;
           }
           if(!flag) break;
       }
       if(flag)  cout<<"tautology"<<endl;
       else cout<<"not"<<endl;
   }
}

 

posted @ 2017-04-15 16:43  Mel年  阅读(223)  评论(0编辑  收藏  举报