algo_156(藍橋杯) 表達式計算
阿新 • • 發佈:2018-03-08
+= 後序表達式 ase name urn cal break pen esp
問題描述
輸入一個只包含加減乖除和括號的合法表達式,求表達式的值。其中除表示整除。
輸入格式
輸入一行,包含一個表達式。
輸出格式
輸出這個表達式的值。
樣例輸入
1-2+3*(4-5)
樣例輸出
-4
數據規模和約定
表達式長度不超過100,表達式運算合法且運算過程都在int內進行。
#include<iostream> #include<cstdio> #include<stack> #include<vector> #include<cstring> #include<cctype> using namespacestd; //#define LOCAL struct Node { int key; // 為0時表示當前節點為操作數,為1表示為操作符; int number; char oper; }a[105]; //存放拆解後的表達式 stack<Node> analytic; stack<Node> calc; //存放後序表達式 vector<Node> post; int main() { #ifdef LOCAL freopen("algo_156.txt", "r", stdin); #endif stringstr; int num_a = 0; cin >> str; //解決負數開頭的問題 if(str[0] == ‘-‘) { string str1 = "0"; str = str1 + str; } //解析表達式 int len = str.length(); for(int i = 0; i < len; i++) { int num = 0; int temp = 0; while(str[i] != ‘\0‘ && isdigit(str[i])) { temp= 1; num *= 10; num += (str[i] - ‘0‘); i++; } if(temp == 1) { a[num_a].key = 0; a[num_a].number = num; post.push_back(a[num_a]); num_a++; } if(str[i] == ‘(‘) { a[num_a].key = 1; a[num_a].oper = ‘(‘; analytic.push(a[num_a]); num_a++; } else if(str[i] == ‘)‘) { while(!analytic.empty() && analytic.top().oper != ‘(‘) { post.push_back(analytic.top()); analytic.pop(); } if(analytic.top().oper == ‘(‘) analytic.pop(); } else if(str[i] == ‘+‘ || str[i] == ‘-‘) { while(!analytic.empty() && analytic.top().oper != ‘(‘) { post.push_back(analytic.top()); analytic.pop(); } a[num_a].key = 1; a[num_a].oper = str[i]; analytic.push(a[num_a]); num_a++; } else if(str[i] == ‘*‘ || str[i] == ‘/‘) { while(!analytic.empty() && (analytic.top().oper == ‘*‘ || analytic.top().oper == ‘/‘)) { post.push_back(analytic.top()); analytic.pop(); } a[num_a].key = 1; a[num_a].oper = str[i]; analytic.push(a[num_a]); num_a++; } } //將棧中元素釋放 while(!analytic.empty()) { post.push_back(analytic.top()); analytic.pop(); } //輸出後序表達式 /* for(int m = 0; m < post.size(); m++) { if(post[m].key == 1) cout << post[m].oper; else cout << post[m].number; } cout << endl; */ //計算後序表達式 for(int j = 0; j < post.size(); j++) { if(post[j].key == 0) { calc.push(post[j]); } else if(post[j].key == 1) { int s, left, right; right = calc.top().number; calc.pop(); left = calc.top().number; switch(post[j].oper) { case ‘+‘ : s = left + right;break; case ‘-‘ : s = left - right;break; case ‘*‘ : s = left * right;break; case ‘/‘ : s = left / right;break; default : return -1; } calc.top().number = s; } } int sum = calc.top().number; cout << sum << endl; return 0; }
algo_156(藍橋杯) 表達式計算