题目1101:计算表达式

来源:互联网 发布:虎视眈眈单人动作数据 编辑:程序博客网 时间:2024/06/05 02:44

#include "iostream"#include "stdio.h"#include <vector>#include <cstring>#include <algorithm>#include <string>#include <string.h>#include <stack>using namespace std;//1101int op(int c){    if(c=='*'||c=='/') return 2;    if(c=='+'||c=='-') return 1;    else return 0;}bool isDig(char c){    if(c>='0'&&c<='9') return true;    else               return false;}int cal(int x,int y,char c){    if(c=='+') return x+y;    if(c=='-') return x-y;    if(c=='*') return x*y;    if(c=='/') return x/y;}void fuck(char s[]){    stack<int> a;    stack<char> ch;    while(!a.empty()) a.pop();    while(!ch.empty()) ch.pop();    int i,t,l=strlen(s);    char c;    ch.push('#');    s[l++]='#';    for(i=0;i<l;i++){        if(isDig(s[i])){            sscanf(s+i,"%d",&t);            a.push(t);            while(isDig(s[i+1]))                i++;        }        else{            if(ch.empty())  ch.push(s[i]);            else{                c=ch.top();                if( op(s[i])-op(c) > 0){                    ch.push(s[i]);                }                else{                    while( op(c)-op(s[i]) >=0 ){                        if(ch.top()=='#')       {cout<<a.top()<<endl;return;}                        int y=a.top();a.pop();                        int x=a.top();a.pop();                        a.push(cal(x,y,c));                        ch.pop();                        c=ch.top();                    }                    ch.push(s[i]);                }            }        }    }  }char s[10010]; int main(){    //freopen("input.txt","r",stdin);    while(scanf("%s",s)!=EOF){        fuck(s);    }    return 0;}/**************************************************************    Problem: 1101    User: cust123    Language: C++    Result: Accepted    Time:0 ms    Memory:1532 kb****************************************************************/


0 0
原创粉丝点击