EOJ_1024_表达式
生活随笔
收集整理的這篇文章主要介紹了
EOJ_1024_表达式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <bits/stdc++.h>using namespace std;
//此方法與視頻中的方法不太一致,不是先轉化成后綴表達式后再計算
//而是邊轉換邊計算
//先轉換再計算缺點:會導致儲存后綴表達式的stack內部數字無法辨別是符號還是計算出的結果
//需要另外設計
stack<int> res;
stack<char> sign;
int table[130]={0};//優先級void init(int table[])
{table['-']=1;table['+']=1;table['*']=2;table['/']=2;table['(']=0;table[')']=0;
}
//這里要注意是&
void cal(stack<int> &res, char sign)
{int tmp2 = res.top();res.pop();int tmp1 = res.top();res.pop();if(sign=='-') res.push(tmp1-tmp2);if(sign=='+') res.push(tmp1+tmp2);if(sign=='*') res.push(tmp1*tmp2);if(sign=='/') res.push(tmp1/tmp2);
}int main()
{init(table);string s;cin>>s;int len=s.size();int i=0;//因為循環中涉及到i的++,所以不用forwhile(i<len){if(isdigit(s[i])){int tmp=0;while(i<len &&isdigit(s[i])){tmp = tmp*10+s[i]-'0';i++;}res.push(tmp);}else{if(s[i]=='-'){if(i==0 ||s[i-1]=='('){int tmp=0;i++;while(i<len &&isdigit(s[i])){tmp = tmp*10+s[i]-'0';i++;}res.push(-1*tmp);}else{while(!sign.empty() &&table[s[i]]<=table[sign.top()]){cal(res, sign.top());sign.pop();}sign.push(s[i]);i++;}}else{if(s[i]=='(') sign.push('(');else if(s[i]==')'){while(sign.top()!='('){cal(res, sign.top());sign.pop();}sign.pop();}else{while(!sign.empty() &&table[s[i]]<=table[sign.top()]){cal(res, sign.top());sign.pop();}sign.push(s[i]);}i++;}}}while(!sign.empty()){cal(res, sign.top());sign.pop();}cout<<res.top()<<endl;return 0;
}
總結
以上是生活随笔為你收集整理的EOJ_1024_表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EOJ_1007_环形双向链表
- 下一篇: EOJ_1039_最长连续公共子序列