1686:等價表達式
- 總時間限制:
- 1000ms
- 內存限制:
- 65536kB
- 描述
- 判斷兩個表達式在數學上是否是等價的。
- 輸入
- 第一行:N(1<=N<=20),表示測試數據組數。
接下來每組測試數據包括兩行,每行包括一個數學表達式,每個表達式的長度不超過80個字符。輸入數據沒有空行。
一個表達式可能包括:
單個英文字母表示的變量(區分大小寫)
數字(只有一位數)
配對的括號
運算符加+、減-、乘*
任意數量的空格或tab(可能出現在表達式中間的任何位置)
注意:表達式保證是語法正確的,且所有運算符的優先級相同,運算次序從左至右。變量的係數和指數保證不超過16位整數。 - 輸出
- 對每個測試數據,輸出一行:等價則輸出“YES”,不等價則輸出“NO”。
- 樣例輸入
-
3 (a+b-c)*2 (a+a)+(b*2)-(3*c)+c a*2-(a+c)+((a+c+e)*2) 3*a+c+(2*e) (a-b)*(a-b) (a*a)-(2*a*b)-(b*b)
- 樣例輸出
-
YES YES
NO
-
個人理解:參考百度答案
-
-
#include <cstdio> #include <iostream> #include <string> #include <cstring> #include <stack> using namespace std; #define MAX 100 string change(char *p) { string cnt; int len=strlen(p); stack<char>astack; for(int i=0; i<=len; i++) { if((p[i]>='0' && p[i]<='9') || (p[i]>='a' && p[i]<='z')) cnt+=p[i]; else if(p[i]=='(') astack.push('('); else if(p[i]==')') { while(astack.top()!='(') { cnt+=astack.top(); astack.pop(); } astack.pop(); } else if(p[i]=='+' || p[i]=='-') { while(!astack.empty() && astack.top()!='(') { cnt+=astack.top(); astack.pop(); } astack.push(p[i]); } else if(p[i]=='*') { while(!astack.empty() && astack.top()!='(' && astack.top()=='*') { cnt+=astack.top(); astack.pop(); } astack.push(p[i]); } else if(p[i]==' ' || p[i]==' ') continue; } while(!astack.empty()) { cnt+=astack.top(); astack.pop(); } return cnt; } int getsum(string num) { int len=num.length(); stack<int>astack; for(int i=0; i<len; i++) { if(num[i]<='z' && num[i]>='a') { int ascii=num[i]; astack.push(ascii); } else if(num[i]>='0' && num[i]<='9') astack.push((int)num[i]-'0'); else if(num[i]=='+') { int n=astack.top(); astack.pop(); int m=astack.top(); astack.pop(); m+=n; astack.push(m); } else if(num[i]=='*') { int n=astack.top(); astack.pop(); int m=astack.top(); astack.pop(); n*=m; astack.push(n); } else if(num[i]=='-') { int n=astack.top(); astack.pop(); int m=astack.top(); astack.pop(); m-=n; astack.push(m); } } int result=astack.top(); astack.pop(); return result; } int main() { int N; scanf("%d", &N); cin.get(); while(N--) { char s1[MAX], s2[MAX]; cin.getline(s1, MAX); string p1=change(s1); int a=getsum(p1); cin.getline(s2, MAX); string p2=change(s2); int b=getsum(p2); if(a==b) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }