Because this topic explains the precedence rules, it is possible to operate directly from left to right, and in the case of nested parentheses, you can use a recursive method, given the right and left bounds of each parenthesis, with the pseudo-code as follows:
int Cal () {
if (parentheses) sum + = Cal ();
else sum + = num;
return sum;
}
But this topic really pits me a bit, saw WA, have not seen tle ... Because I did not see a space for this condition, wireless tle, but also to eliminate the function is to use the array simulation stack, in fact, is read into error and forget to deal with the space, changed, after the successful AC. The code is as follows:
#include <iostream>#include<cmath>#include<vector>#include<algorithm>#include<cstdio>#include<cstring>#include<stack>using namespacestd;#defineMAXN 100intPOS[MAXN],ST[MAXN];intCal (intIdConst Char*a) { intsum =0, TMP; for(inti = id+1; I < pos[id];i++){ if(A[i] = ='(') {tmp=Cal (i,a); if(a[i-1]=='('|| a[i-1]=='+') Sum + =tmp; Else if(a[i-1]=='-') Sum-=tmp; Else if(a[i-1]=='*') Sum *=tmp; I=Pos[i]; } Else if((a[i]>='a'&&a[i]<='Z')|| (a[i]>='0'&&a[i]<='9')){ if(a[i]>='a'&&a[i]<='Z') tmp = (a[i]-'a'+1); ElseTMP = a[i]-'0'; if(a[i-1]=='('|| a[i-1]=='+') Sum + =tmp; Else if(a[i-1]=='-') Sum-=tmp; Else if(a[i-1]=='*') Sum *=tmp; I++; } } returnsum;}intGetnum (Const Char*a) {memset (pos,0,sizeof(POS)); memset (St,0,sizeof(ST)); intLen =strlen (a); inttop =0; for(inti =0; I < len;i++) { if(a[i]=='(') st[top++] =i; if(a[i]==')') {pos[st[--top]] =i; } } intsum =0, TMP; for(inti =0; I < len;i++){ if(a[i]=='(') {tmp=Cal (i,a); if(i = =0|| a[i-1]=='+') Sum+=tmp; Else if(a[i-1] =='-') Sum-=tmp; Else if(a[i-1] =='*') Sum *=tmp; I=Pos[i]; } Else if((a[i]>='a'&&a[i]<='Z')|| (a[i]>='0'&&a[i]<='9')){ if(a[i]>='a'&&a[i]<='Z') tmp = (a[i]-'a'+1); ElseTMP = a[i]-'0'; if(i = =0|| a[i-1]=='+') Sum+=tmp; Else if(a[i-1] =='-') Sum-=tmp; ElseSum *=tmp; I++; } } //printf ("The num =%d\n", sum); returnsum;}intMain () {intT,lena,lenb,num1,num2,tot; CharA[MAXN],B[MAXN]; scanf ("%d",&t); GetChar (); while(t--) {gets (a); Lena=strlen (a); Tot=0; for(inti =0; I < lena;i++){ if(a[i]==' ')Continue; Elseb[tot++] =A[i]; } B[tot]=' /'; NUM1=Getnum (b); Gets (a); Lena=strlen (a); Tot=0; for(inti =0; I < lena;i++){ if(a[i]==' ')Continue; Elseb[tot++] =A[i]; } B[tot]=' /'; Num2=Getnum (b); if(NUM1 = = num2) puts ("YES"); ElsePuts"NO"); } return 0;}
Uvalive 2056Lazy Math Instructor (recursive processing of nested parentheses)