目前只能算单位数,可计算括号与加减乘除。
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 4 const int maxn = 1000; 5 int lch[maxn],rch[maxn]; 6 char op[maxn]; 7 int nc = 0,n; 8 char s[1000]; 9 10 int build_tree(char* s, int x , int y) 11 { 12 int c1 = -1,c2 = -1,p = 0; //c1存储是否有+,-出现,c2存储*,/ 13 int u; //u存储节点编号 14 if (y - x == 1) //只能处理单位数字!!! 15 { 16 u = ++nc; 17 lch[u] = rch[u] = 0; 18 op[u] = s[x]; 19 return u; 20 } 21 for (int i = x; i<y; i++) 22 { 23 switch(s[i]) 24 { 25 case ‘(‘: p++; break; 26 case ‘)‘: p--; break; 27 case ‘+‘: case ‘-‘: if (!p) c1 = i; break; 28 case ‘*‘: case ‘/‘: if (!p) c2 = i; break; 29 //p存储当前是否在括号内,如在括号内则不取当前符号 30 } 31 } 32 if (c1<0) c1 = c2; 33 if (c1<0) return build_tree(s,x+1,y-1); 34 u = ++nc; 35 lch[u] = build_tree(s,x,c1); 36 rch[u] = build_tree(s,c1+1,y); 37 op[u] = s[c1]; 38 return u; 39 } 40 41 char getstring() //字符串读入 42 { 43 int i = -1; 44 char c = getchar(); 45 do 46 { 47 if (c==‘\n‘ || c==‘\0‘) break; 48 s[++i] = c; 49 c = getchar(); 50 }while (1); 51 n = i+1; 52 } 53 54 int count(int u) //计算 55 { 56 if (lch[u] == 0) 57 { 58 int num; 59 num = (int)op[u] - ‘0‘; //只能处理单位数字!! 60 return num; 61 }else 62 { 63 switch(op[u]) 64 { 65 case ‘*‘: return count(lch[u])*count(rch[u]); 66 case ‘/‘: return count(lch[u])/count(rch[u]); 67 case ‘+‘: return count(lch[u])+count(rch[u]); 68 case ‘-‘: return count(lch[u])-count(rch[u]); 69 } 70 } 71 } 72 /* 73 int print(int u,int a) //输出表达式树 74 { 75 int d = 0; 76 if (!u) return 0; 77 if (a) 78 printf("(%c",op[u]); 79 else printf(",%c",op[u]),d = 1; 80 print(lch[u],1); 81 print(rch[u],0); 82 if (d) printf(")"); 83 } 84 */ 85 int main() 86 { 87 int ans; 88 getstring(); 89 build_tree(s,0,n); 90 // print(1,1); printf(")\n"); //输出表达式树 91 ans = count(1); 92 printf("%d",ans); 93 }
时间: 2024-10-13 18:13:05