poj1686

来源:互联网 发布:淘宝燕山大学河北大街 编辑:程序博客网 时间:2024/06/03 17:26

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

题意:判断两个公式是否正确,它不是判断两个式子是否一样,二是判断结果。

今天下午老师讲数据结构,讲完了栈,做几道题练练吧题意://栈 中缀转化为后缀//基本规则://1.读到一个操作数时,立即输出该数,操作符不立即输出.(你可以存在一个临时数组中)//2.比较栈顶操作符与遇到的输入操作符之间的优先级,如果栈顶操作符的优先级高,则出栈。否则,压栈。//3.遇到(,压栈,直到遇到)出栈。#include<iostream>#include<cstdio>#include<string.h>#include<map>#include<stack>#define max 101using namespace std;map<char,int> ma;char root[max];int Judge(char a){    if(a>='a'&&a<='z'||a>='A'&&a<='Z'||a>='1'&&a<='9')     return 1;     return 0;}void Convert(char ch[]){    /* for(int i=0;i<strlen(ch);i++)         printf("%c",ch[i]);         printf("\n");         */    stack<char> start;    int len=strlen(ch);   // printf("%d\n",len);    int i;    int Top=0;    for(i=0;i<len;i++)    {        if(Judge(ch[i]))        {            root[Top++]=ch[i];        }        else        {          switch( ch[i] )          {         //     printf("fdsdfsd\n");              case '(':                  start.push( ch[i] );                  break;              case ')':                  while(start.top()!='(')                  {                      root[Top++]=start.top();//将()内的数放的临时数组中。                      start.pop();                  }                  start.pop();//pop()出')';                  break;             case '+':             case '-':             case '*':             while((!start.empty())&&ma[start.top()]>=ma[ch[i]])             {                 root[Top++]=start.top();                 start.pop();             }              start.push(ch[i]);              break;          }        }    }    while(!start.empty())    {        root[Top++]=start.top();        start.pop();    }    root[Top]=0;}int sum(){    stack<int> end;    int len=strlen(root);    int i;    for( i=0;i<len;i++)    {        if(Judge(root[i]))        {            if(root[i]>='1'&&root[i]<='9')              end.push(root[i]-'0');            else             end.push((int)root[i]);        }        else        {            int num1,num2;            num1=end.top();            end.pop();            num2=end.top();            end.pop();            switch(root[i])            {                case '*':                 end.push(num1*num2);                 break;                case '-':                end.push(num2-num1);                break;                case '+':                end.push(num1+num2);                break;            }        }    }    return end.top();}int main(){    char cha1[max],cha2[max];    int N;     ma['+']=2;     ma['-']=2;     ma['*']=3;     ma['(']=1;     cin>>N;    getchar();    int a,b;    while(N--)    {        cin.getline(cha1,100,'\n');        cin.getline(cha2,100,'\n');        Convert(cha1);        a=sum();        Convert(cha2);        b=sum();        if(a==b)          cout<<"YES"<<endl;        else          cout<<"NO"<<endl;    }    return 0;}