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;
}