测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A32867. 表达式求值输入一个布尔表达式,请你输出它的真假值。比如:( V | V ) & F & ( F | V )V表示true,F表示false,&表示与,|表示或,!表示非。上式的结果是F输入输入包含多行,每行一个布尔表达式,表达式中可以有空格,总长度不超过1000输出对每行输入,如果表达式为真,输出"V",否则出来"F"样例输入( V | V ) & F & ( F| V) !V | V & V …

填空题 中等

题目描述

表达式求值

输入一个布尔表达式,请你输出它的真假值。

比如:( V | V ) & F & ( F | V )

V表示true,F表示false,&表示与,|表示或,!表示非。

上式的结果是F

输入

输入包含多行,每行一个布尔表达式,表达式中可以有空格,总长度不超过1000

输出

对每行输入,如果表达式为真,输出"V",否则出来"F"

样例输入

( V | V ) & F & ( F| V)
!V | V & V & !F & (F | V ) & (!F | F | !V & V)
(F&F|V|!V&!F&!(F|F&V))

样例输出

F
V
V

参考答案

#include<cstdio> #include<cstring> #include<map> #include<algorithm> #include<iostream> using namespace std; bool a[1005]; int opt[1005]; int atot; void work(int x){ switch(x){ case 1: a[atot-2]|=a[atot-1]; --atot; break; case 2: a[atot-2]&=a[atot-1]; --atot; break; case 3:a[atot-1]=!a[atot-1]; } } int main(){ freopen("bool.in","r",stdin); char s[1005]; int len,i,j,tmp; int otot=0; while(gets(s)){ len=strlen(s); for(i=0;i<len;++i) if(s[i]!=' '){ if(s[i]=='V'||s[i]=='F')a[atot++]=s[i]=='V'; else if(s[i]=='(')opt[otot++]=0; else if(s[i]==')') while(otot&&opt[--otot]) work(opt[otot]); else if(s[i]=='!')opt[otot++]=3; else{ tmp=s[i]=='|'?1:2; while(otot&&opt[otot-1]>=tmp)work(opt[--otot]); opt[otot++]=tmp; } /*printf("--------:%c\n",s[i]); for(j=0;j<atot;++j)printf("%d ",a[j]); puts(""); for(j=0;j<otot;++j)printf("%d ",opt[j]); puts("");*/ } if(atot==0)continue; while(otot)work(opt[--otot]); if(a[--atot])puts("V"); else puts("F"); } }
上一题 下一题