zoukankan      html  css  js  c++  java
  • (栈的应用5.2.2)POJ 2106 Boolean Expressions(表达式求值)

    /*
     * 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()) != '
    ' && c != EOF);
    
    		while(otop){//将op栈中的所有元素出栈进行运算
    			calc();
    		}
    
    		printf("Expression %d: ",counter++);
    		printf(val[0]?"V":"F");
    		printf("
    ");
    	}
    
    	return 0;
    }
    
    


  • 相关阅读:
    codeforces
    hdu
    hdu
    poj 2823
    hdu
    hdu
    hdu
    微信公众号 SDK
    PHP 正则表达式
    注册和登录时的验证码
  • 原文地址:https://www.cnblogs.com/james1207/p/3424031.html
Copyright © 2011-2022 走看看