#include<stdio.h> #include<cstdio> #include<string> #include<queue> #include<map> #include<stack> #include<iostream> using namespace std; struct node{ double num ; char op ; bool flag ; }; string str ; map<char, int> op; queue<node> q; stack<node> s; void change() { double num ; node temp ; int i ; for(i=0;i<str.length();) { if(str[i]>='0'&&str[i]<='9') { temp.flag =true; temp.num = str[i++]-'0'; while(i<str.length()&&str[i]>='0'&&str[i]<='9') { temp.num =temp.num*10+str[i]-'0'; i++; } q.push(temp); } else{ temp.flag = false; while(!s.empty()&&op[str[i]]<=op[s.top().op]) { q.push(s.top()); s.pop(); } temp.op=str[i]; s.push(temp); i++; } } while(!s.empty()) { q.push(s.top()); s.pop(); } } double Cal() { double temp1,temp2; node cur, temp; while(!q.empty()) { cur = q.front(); q.pop(); if(cur.flag ==true) s.push(cur); else{ temp2 = s.top().num; s.pop(); temp1 = s.top().num; s.pop(); temp.flag = true ; if(cur.op=='+') temp.num =temp1+temp2; else if(cur.op=='-') temp.num = temp1-temp2; else if(cur.op =='*') temp.num = temp1*temp2; else temp.num = temp1/temp2; s.push(temp); } } return s.top().num; } int main() { op['+']=op['-']=1; op['/']=op['*']=2; while(getline(cin,str),str!="0"){ for(string::iterator it = str.end();it!=str.begin();it--) { if(*it==' ') str.erase(it);} while(!s.empty()) s.pop(); change(); printf("%.2f\n",Cal()); } return 0; }

好难。。。快100行代码。全是bug,。。。。

题目出处http://codeup.hustoj.com/contest.php?cid=100000605

解答来自:算法笔记,我基本照抄思想。。。

posted on 2017-10-09 22:55  暮雨煙深淺  阅读(166)  评论(0编辑  收藏  举报