这个题没有什么好说的,只要细心就好了. /* ID: mnlm1991 PROG: hdoj 3000 LANG: C++ */ #include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<vector> #include<algorithm> #include<string> #include<map> #include<set> #include<bitset> #include<queue> #include<stack> #include<iostream> using namespace std; map <string, int> sim; char s[1000001]; int Deal(string tmp) { if (isdigit(tmp[0]) || tmp[0] == '-') { return atoi(tmp.c_str()); } else { return sim[tmp]; } } int DFS(char * &s) { string tmp; tmp.clear(); stack <int> num; stack <char> op; while (!op.empty()) { op.pop(); } while (!num.empty()) { num.pop(); } char ch; int x; int y; for (; *s != ')'; s++) { switch(*s) { case '(' : num.push(DFS(++s)); break; case '=' : num.push(sim[tmp] = DFS(++s)); s--; tmp.clear(); break; case '+' : case '-' : if (*s == '-' && (*(s - 1) == '(' || *(s - 1) == '=')) { tmp.push_back(*s); break; } if (!tmp.empty()) { x = Deal(tmp); tmp.clear(); } else { x = num.top(); num.pop(); } if (!op.empty() && !num.empty()) { ch = op.top(); op.pop(); y = num.top(); num.pop(); if (ch == '+') { num.push(y + x); } else if (ch == '-') { num.push(y - x); } else if (ch == '*') { num.push(y * x); } else { num.push(y / x); } } else { num.push(x); } op.push(*s); break; case '*' : case '/' : if (!tmp.empty()) { x = Deal(tmp); tmp.clear(); } else { x = num.top(); num.pop(); } if (!op.empty() && !num.empty()) { ch = op.top(); switch(ch) { case '+' : case '-' : num.push(x); break; case '*' : y = num.top(); num.pop(); num.push(y * x); op.pop(); break; case '/' : y = num.top(); num.pop(); num.push(y / x); op.pop(); default :; } } else { num.push(x); } op.push(*s); break; default : tmp.push_back(*s); break; } } if (!tmp.empty()) { num.push(Deal(tmp)); tmp.clear(); } while (!op.empty()) { ch = op.top(); op.pop(); y = num.top(); num.pop(); x = num.top(); num.pop(); switch(ch) { case '+' : num.push(x + y); break; case '-' : num.push(x - y); break; case '*' : num.push(x * y); break; case '/' : num.push(x / y); default :; } } return num.top(); } int main() { char * p; sim.clear(); s[0] = '('; while (scanf("%s", s + 1) != EOF) { int len = strlen(s); if (s[len -1] == ';') { len--; } s[len++] = ')'; s[len++] = ')'; p = s; printf("%d/n", DFS(p)); } return 0; }