您的位置:首页 > 其它

(栈的应用5.2.2)POJ 2106 Boolean Expressions(表达式求值)

2013-11-14 20:24 411 查看
/*
* POJ_2106.cpp
*
*  Created on: 2013年10月30日
*      Author: Administrator
*/

#include <iostream>
#include <cstdio>

using namespace std;

const int maxn = 110;

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

void insert(int b){//将操作数b压入操作数栈val
while(otop && op[otop - 1] == 3){//在压入之前对b进行!运算
b = !b;
--otop;
}

val[vtop++] = b;
}

void calc(){//进行双目运算
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(){
char c;

int counter = 1;
while((c = getchar()) != EOF){//要理解并记住这种形式的输入输出处理
otop = 0;
vtop = 0;

do{
if( c == '('){
op[otop++] = 0;
}else if(c == ')'){//处理)内的所有运算,结果压入val栈
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){//将op栈中所有优先级比&的运算符出栈进行运算
calc();
}

op[otop++] = 2;//将&压入op栈
}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()) != '\n' && c != EOF);

while(otop){//将op栈中的所有元素出栈进行运算
calc();
}

printf("Expression %d: ",counter++);
printf(val[0]?"V":"F");
printf("\n");
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: