/* ACM North Central Region, 1993-94 Problem D, Evaluating Simple C Expressions Ed Karrels, April 1996 */ #include #include int Token (char s[], int *i) { while (isspace(s[*i])) ++*i; if (!s[*i]) return 0; if (s[*i] == '+') { if (s[*i+1] == '+') { *i += 2; return '*'; } else { ++*i; return '+'; } } if (s[*i] == '-') { if (s[*i+1] == '-') { *i += 2; return '/'; } else { ++*i; return '-'; } } return s[(*i)++]; } #define NT nt = Token(L, &p) int main() { int v[26], i, p, pre, post[26], f=1, sum, vn, used[26]; char L[100], nt; fgets(L, 100, stdin); L[strlen(L)-1] = 0; while (strlen(L)) { printf("Expression: %s\n", L); for (i=0; i<26; i++) { v[i] = i+1; used[i] = 0; post[i] = 0; } f = 1; p = sum = 0; NT; while (1) { pre = 0; if (nt=='*') {pre++; NT;} if (nt=='/') {pre--; NT;} if (!isalpha(nt)) {printf("no var name\n"); exit(1);} vn = nt - 'a'; v[vn] += pre; used[vn] = 1; sum += f*v[vn]; NT; if (nt == '*') {post[vn]++; NT;} if (nt == '/') {post[vn]--; NT;} if (nt==0) break; f = (nt=='+') ? 1 : -1; NT; } printf(" value = %d\n", sum); for (i=0; i<26; i++) if (used[i]) printf(" %c = %d\n", 'a'+i, v[i]+post[i]); fgets(L, 100, stdin); L[strlen(L)-1] = 0; } return 0; }