poj2106 http://poj.org/problem?id=2106

//题意是判断公式的F或V  注意符号的优先级运算
//注意:对于'!',单目表达式的计算,在转后缀的时候,
//需将数值进栈,再将其压入后缀表达式中;
// 注意:题意中字符串的大小不包括空格
#include<iostream>
#include<cstdio>
#include<stack>
#include<map>
#include<string.h>
#define max 120
using namespace std;
char s1[max];
map<char,int> ma;
int Judge(char a)
{
    if(a=='V'||a=='F')
        return 1;
    return 0;
}
void Convect(char ch[])
{
    stack<char> s;
    int len=strlen(ch);
    int sum=-1;
    for(int i=0; i<len; i++)
    {
        if(Judge(ch[i]))
        {
            s1[++sum]=ch[i];
        }
        else if(ch[i]==' ') continue;
        else
        {
            switch(ch[i])
            {
            case '(':
                s.push(ch[i]);
                break;
            case ')':
                while(s.top()!='(')
                {
                    s1[++sum]=s.top();
                    s.pop();
                }
                s.pop();
                break;
            case '!':
               s.push('!');//直接压入
               break;
            case '&':
            case '|':
                while((!s.empty())&&ma[s.top()]>=ma[ch[i]])
                {
                    s1[++sum]=s.top();
                    s.pop();
                }
                s.push(ch[i]);
                break;
            }
        }
    }
    while(!s.empty())
    {
        s1[++sum]=s.top();
        s.pop();
    }
    s1[++sum]=0;
   /* for(int i=0;i<sum;i++)
     printf("%c",s1[i]);
     printf("\n");
     */
}
char Result()
{
    int op[max];
    int len=strlen(s1);
    int add=-1;
    for(int i=0; i<len; i++)
    {
        if(s1[i]=='V')
        {
            op[++add]=1;
        }
        else if(s1[i]=='F')
         {
             op[++add]=0;
         }
         else
         {
             switch(s1[i])
             {
                 case '|':
                 op[add-1]|=op[add];
                 add--;
                 break;
                 case '&':
                    op[add-1]&=op[add];
                    add--;
                  break;
                 case '!':
                    op[add]=!op[add];
                    break;
             }
         }
    }
     return op[add];
}
int main()
{
    char cha[max];
    //优先级留最低的
    ma['&']=2;
    ma['!']=3;
    ma['|']=1;
    int ans;
    int add=1;
    while(cin.getline(cha,max))
    {

        Convect(cha);
      //  printf("sdfds\n");
        ans=Result();
        if(ans)
            printf("Expression %d: V\n",add++);
        else
            printf("Expression %d: F\n",add++);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值