poj 2106 Boolean Expressions 课本代码


#include<cstdio>
const int maxn=100 +10;

int val[maxn],vtop;
int op[maxn],otop;

void insert(int b)
{
	while(otop &&op[otop-1]==3)
	{
		b=!b;
		--otop;
	}
	val[vtop++]=b;
}

void calc(void)
{
	int b=val[--vtop];
	int a=val[--vtop];
	int opr=op[--otop];
	
	
	int c=(a&b);
	if(opr==1)
		c=(a|b);
	insert(c);
}

int main(void)
{
	int loop=0;
	
	
	char c;
	while((c=getchar())!=EOF)
	{
		vtop=otop=0;
		
		do
		{
			if(c=='(')
			{
				op[otop++]=0;
			}
			else if(c==')')
			{
				while(otop&&op[otop-1]!=0)
					calc();
				--otop;
				insert(val[--vtop]);//  当表达式是!()时,这一句是计算完 () 后,计算 前面的 ! 的
			}
			else if(c=='!')
			{
				op[otop++]=3;
			}
			else if(c=='&')
			{
				while(otop&&op[otop-1]>=2)
					calc();
				op[otop++]=2;
			}
			else if(c=='|')
			{
				while(otop&&op[otop-1]>=1)
					calc();
				op[otop++]=1;
			}
			else if(c=='V'||c=='F')
			{
				insert(c=='V'?1:0);
			}
		}
		while((c=getchar())!='
'&&c!=EOF);
		while(otop)
			calc();
		
		printf("Expression %d: %c
",++loop,(val[0]?'V':'F'));
	}
	return 0;
	
}



原文地址:https://www.cnblogs.com/gongpixin/p/4477467.html