表达式求值

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
#include<vector>
#include<stack>
#include<list>
#include<iostream>
#include<map>
using namespace std;
#define inf 0x3f3f3f3f
#define Max 110
int max(int a,int b)
{
	return a>b?a:b;
}
int min(int a,int b)
{
	return a<b?a:b;
}
int num[100];
int topnum,topop,tailnum,tailop;
char op[100];
inline int judge(char op1,char op2)
{
    if(((op1=='+'||op1=='-')&&(op2=='+'||op2=='-'||op2==')'))||((op1=='*')&&(op2=='*'||op2=='+'||op2=='-'||op2==')')))
        return 1;
    else if(op1=='('&&op2==')')
        return 0;
    else
        return -1;
}
inline int cal(int a,int b,char op)
{
    if(op=='+') return a+b;
    else if(op=='-') return a-b;
    else return a*b;
}
inline int solve(char str[])
{
    int i;
    topnum=topop=tailnum=tailop=0;
    int len=strlen(str);
    int cnt=0;
    for(i=0;i<len;i++)
    {
        if(str[i]!=' ')
            str[cnt++]=str[i];
    }
    str[cnt]=')';
    i=0;
    op[++topnum]='(';
   // op.push('(');
    while(i<=cnt)
    {
       // printf("a\n");
        if(str[i]!='+'&&str[i]!='-'&&str[i]!='*'&&str[i]!='('&&str[i]!=')')
        {
            if(str[i]>='0'&&str[i]<='9')
                num[++topnum]=str[i]-'0';
            else
                num[++topnum]=str[i];
            i++;
        }
        else
        {
            int tmp=judge(op[topop],str[i]);
          //  printf("i %d tmp %d\n",i,tmp);
            if(tmp==1)
            {
                int a,b;
                a=num[topnum];
                topnum--;
                b=num[topnum];
                topnum--;
                num[++topnum]=cal(b,a,op[topop]);
             //  printf("num %d\n",num.top());
                topop--;
               // op.push(str[i]);
            }
            else if(tmp==0)
            {
                topop--;
                i++;
            }
            else
            {
                op[++topop]=str[i];
                i++;
            }
        }
    }
    return num[topnum];
}
int main()
{
    int n;
    char str[100];
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        int tmp1,tmp2;
        gets(str);
        tmp1=solve(str);
        gets(str);
        tmp2=solve(str);
      //  printf("tmp1 %d tmp2 %d\n",tmp1,tmp2);
        if(tmp1==tmp2)
            printf("YES\n");
        else
            printf("NO\n");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值