题意:模拟运算
解题思路:表达式数构建 模拟(ztw同学的算法)
解题代码
表达式树
// File Name: 表达式树.c // Author: darkdream // Created Time: 2013年04月18日 星期四 19时37分36秒 #include<stdio.h> #include<string.h> #include<stdlib.h> #include<time.h> #include<math.h> int num[50]; const int maxn = 1000; int lch[maxn] , rch[maxn]; char op[maxn]; int nc = 0; int ok = 1; int build_tree(char *s,int x,int y) { //printf("%d****%d\n",x,y); int i , c1 =-1, c2 = -1, p =0; int u ; if(y - x == 1) { u = ++nc; lch[u] = rch[u] = 0 ; op[u] = s[x]; return u ; } for(int i = x; i < y ; i++) { switch(s[i]) { case '(' :p++;break; case ')' :p--;break; case '+':case '-':if(!p) c1 = i ; break; case '*':case '/':if(!p) c2 = i ;break; } } if(c1 < 0) c1 = c2; if(c1 < 0) return build_tree(s,x+1,y-1); u = ++nc; lch[u] = build_tree(s,x,c1); rch[u] = build_tree(s,c1+1,y); op[u] = s[c1]; return u ; } long long find(int i) { if(lch[i] == 0) { return num[op[i]-'a']; } if (op[i] == '+') return find(lch[i])+find(rch[i]); if (op[i] == '-') return find(lch[i])-find(rch[i]); if (op[i] == '*') return find(lch[i])*find(rch[i]); if (op[i] == '/') { if(find(rch[i]) == 0) { ok = 0; return find(lch[i])/1; } else return find(lch[i])/find(rch[i]); } } int main(){ //freopen("/home/plac/problem/input.txt","r",stdin); //freopen("/home/plac/problem/output.txt","w",stdout); char s[1000]; while(scanf("%s",s) != EOF) { memset(lch,0,sizeof(lch)); memset(rch,0,sizeof(lch)); memset(op,0,sizeof(op)); memset(num,0,sizeof(num)); nc = 0; ok = 1; char c = 'a'; char str[56] ={0}; int k = -1; int temp = 0; for(int i = 0;i < strlen(s);i ++) { if(s[i] <= '9' && s[i] >= '0') { temp = temp*10 +(s[i]-'0'); } else { str[++k] = c; num[c-'a'] = temp; c++; str[++k] = s[i]; temp = 0; } if(i == strlen(s)-1) { str[++k] = c; num[c-'a'] = temp; } } build_tree(str,0,strlen(str)); int ans = find(1); if(!ok) printf("impossible\n"); else printf("%lld\n",find(1)); } return 0 ; }
ztw的模拟
View Code
#include<stdio.h> #include<string.h> #define LL long long int main() { LL d[10000] , temp , count; LL i , j; char ch[200]; while(gets(ch)) { count=temp=0; for(j=0 ; j<strlen(ch) ; j++) { if(ch[j]>='0'&&ch[j]<='9') temp = temp*10+ch[j]-'0'; else break; } d[count++]=temp; for(i=j ; i<strlen(ch) ; i++) { temp=0; for(j=i+1 ; ch[j]>='0'&&ch[j]<='9' ; j++) temp = temp*10+ch[j]-'0'; if(ch[i]=='*') d[count-1] *= temp; else if(ch[i]=='/') d[count-1] /= temp; else if(ch[i]=='+') d[count++] = temp; else d[count++] = (-1)*temp; i=j-1; } for(i=1 ; i<count ; i++) d[0]+=d[i]; printf("%lld\n",d[0]); } return 0; }
没有梦想,何谈远方