因为这个题目说明了优先级的规定,所以可以从左到右直接运算,在处理嵌套括号的时候,可以使用递归的方法,给定每一个括号的左右边界,伪代码如下:
int Cal(){
if(括号) sum += Cal();
else sum += num;
return sum;
}
但是这个题目着实坑了我一下,见过WA了,没见过TLE呢……我因为没有看到有空格这个条件,无线TLE,又是消除函数又是改用数组模拟栈,其实就是读入出错和忘记了处理空格,改了之后,成功AC了。代码如下:
#include<iostream> #include<cmath> #include<vector> #include<algorithm> #include<cstdio> #include<cstring> #include<stack> using namespace std; #define maxn 100 int pos[maxn],st[maxn]; int Cal(int id,const char *a){ int sum = 0,tmp; for(int i = 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); else tmp = 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++; } } return sum; } int getnum(const char *a){ memset(pos,0,sizeof(pos)); memset(st,0,sizeof(st)); int len = strlen(a); int top = 0; for(int i = 0;i < len;i++) { if(a[i]==‘(‘) st[top++] = i; if(a[i]==‘)‘) { pos[st[--top]] = i; } } int sum = 0,tmp; for(int i = 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); else tmp = a[i]-‘0‘; if(i == 0 || a[i-1]==‘+‘) sum += tmp; else if(a[i-1] == ‘-‘) sum -= tmp; else sum *= tmp; i++; } } //printf("the num = %d\n",sum); return sum; } int main() { int t,lena,lenb,num1,num2,tot; char a[maxn],b[maxn]; scanf("%d",&t); getchar(); while(t--){ gets(a); lena = strlen(a); tot = 0; for(int i = 0;i < lena;i++){ if(a[i]==‘ ‘) continue; else b[tot++] = a[i]; } b[tot] = ‘\0‘; num1 = getnum(b); gets(a); lena = strlen(a); tot = 0; for(int i = 0;i < lena;i++){ if(a[i]==‘ ‘) continue; else b[tot++] = a[i]; } b[tot] = ‘\0‘; num2 = getnum(b); if(num1 == num2) puts("YES"); else puts("NO"); } return 0; }
UVALive 2056 Lazy Math Instructor(递归处理嵌套括号)
原文:http://www.cnblogs.com/jifahu/p/5693313.html