zoukankan      html  css  js  c++  java
  • 堆和队列的应用之——简单计算器




    #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 ",Cal()); } return 0; }

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

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

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

  • 相关阅读:
    linux同一客户端多个git账号的配置
    linux同一台机子上用多个git 账号
    执行ssh-add时出现Could not open a connection to your authentication agent
    国内常用NTP服务器地址及IP
    PHP双引号的隐患
    mysql 累加求和
    php实现Facebook风格的 time ago函数
    Mysql之数据库设计规范
    搭建Git服务器
    win7下如何根据端口号杀掉进程
  • 原文地址:https://www.cnblogs.com/blairwaldorf/p/7643449.html
Copyright © 2011-2022 走看看