POJ 3295 Tautology(构造法 stack)

本文介绍了一种解析逻辑表达式并判断其是否为重言式的算法,通过使用栈结构来处理输入字符串,最终得出32种可能的情况,并进行枚举验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://poj.org/problem?id=3295

题意:给你一个逻辑表达式,让你判断是否是重言式

思路,对串进行解析,借助栈转求出所有情况的结果,一共是32种,枚举一遍!

代码:

#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <stack>
using namespace std;
#define maxn 500
char str[maxn];
stack<char> sta;
map<char,bool> m;
int main(){
    int i,j,k,len;
    char p,q,r,s,t;
    char now,then;
    while(scanf("%s",str)!=EOF){
        if(str[0]=='0') break;
        len=strlen(str);
        m['0']=false;
        m['1']=true;
        for(k=0;k<32;k++){
            while(!sta.empty()) sta.pop();
            m['p']=m['q']=m['s']=m['r']=m['t']=false;
            if(k&1) m['p']=true;
            if(k&2) m['q']=true;
            if(k&4) m['r']=true;
            if(k&8) m['s']=true;
            if(k&16) m['t']=true;
            i=len-1;
            while(i>=0){
                while(str[i]>='a' && i>=0){
                    sta.push(str[i]);
                    i--;
                }
                if(i<0) break;
                if(str[i]=='K'){
                    now=sta.top();
                    sta.pop();
                    then=sta.top();
                    sta.pop();
                    if(m[now] && m[then]) sta.push('1');
                    else sta.push('0');
                }
                else if(str[i]=='A') {
                    now=sta.top();
                    sta.pop();
                    then=sta.top();
                    sta.pop();
                    if(m[now] || m[then]) sta.push('1');
                    else sta.push('0');
                }
                else if(str[i]=='N') {
                    now=sta.top();
                    sta.pop();
                    if(m[now]) sta.push('0');
                    else sta.push('1');
                }
                else if(str[i]=='E') {
                    now=sta.top();
                    sta.pop();
                    then=sta.top();
                    sta.pop();
                    if(m[now] == m[then]) sta.push('1');
                    else sta.push('0');
                }
                else if(str[i]=='C'){
                    now=sta.top();
                    sta.pop();
                    then=sta.top();
                    sta.pop();
                    if(m[now]==false && m[then]==true) sta.push('0');
                    else sta.push('1');
                }
                i--;
            }
            if(m[sta.top()]==false) break;
        }
        if(m[sta.top()]) printf("tautology\n");
        else printf("not\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值