poj1686Lazy Math Instructor

http://poj.org/problem?id=1686

构造栈,表达式求值。我只会C语言。。

#include <stdio.h>
#include <string.h>
char opp[8] = {'+','-','*','/','(',')','#'}; 
int priority[7][7] = {{1,1,-1,-1,-1,1,1},{1,1,-1,-1,-1,1,1},{1,1,1,1,-1,1,1},{1,1,1,1,-1,1,1},{-1,-1,-1,-1,-1,0,-2},{1,1,1,1,-2,1,1},{-1,-1,-1,-1,-1,-2,0}};//算符之间的优先关系
int calculate(int x,int y, char op) 
{
    switch(op)
    {
        case '+':return x+y;
        case '-':return x-y;
        case '*':return x*y;
        case '/':return x/y;
    }
}
int Compare(char a,char b)//比较优先级
{
    int row,col,i;
    for(i=0; i<7; i++)
    {
        if( a == opp[i] )
           row = i;
        if( b == opp[i] )
           col = i;
    }
    return priority[row][col];
}
int result(char str[],int plus)//求表达式的结果
{
    char ch, op, opetator[100];
    int x,y,i=0,count1=0,count2=0,operand[100];
    opetator[count2++] = '#';
    while(str[i]!='#' || opetator[count2-1]!='#')
    {
        ch = str[i];
        if(ch>='0'&&ch<='9')//阿拉伯数字‘0’~‘9’
        {
            operand[count1++] = ch-'0';
            i++;
            continue;
        }
        if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))//英文字母
        {
            operand[count1++] = ch-'a'+plus;
            i++;
            continue;
        }
        if(ch=='+' || ch=='-' || ch=='*' || ch=='(' || ch==')' || ch=='#')//操作符
        {
            switch(Compare(opetator[count2-1],ch))
            {
                case -1: opetator[count2++] = ch; i++; break;//当前元素大于栈顶元素
                case 0 : count2--; i++; break;//当前元素等于栈顶元素
                case 1 : op = opetator[--count2]; y = operand[--count1]; x = operand[--count1]; 
                            operand[count1++] = calculate(x,y,op); break;//当前元素小于栈顶元素
            }
        }
        else
            i++;
    }
    return operand[count1-1];
}
int main()
{
    char fir[90], sec[90];
    int N;
    scanf("%d",&N);
    getchar();
    while(N--)
    {
        gets(fir);
        gets(sec);
        fir[strlen( fir )] = '#';
        sec[strlen( sec )] = '#';
        if(result(fir,10) != result(sec,10))
            printf("NO\n");  
        else
            printf("YES\n");
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值