POJ-1539(表达式求值)

来源:互联网 发布:阿里旺旺网络连接失败 编辑:程序博客网 时间:2024/05/23 13:42

题目:http://poj.org/problem?id=1539


#include <cctype>#include <string>#include <iostream>using namespace std;int  value[26];char used[26], post[26];void preEval(string& exp){    int i = 0, len = exp.size();    for(int k = 0; k < len; ++k){        if(!isspace(exp[k])) exp[i++] = exp[k];    }    exp.resize(len = i);    for(i = 0; i < 26; ++i){        used[i] = 0;        value[i] = i + 1;        post[i] = 0;    }    for(i = 0; i < len; ++i){        if(isalpha(exp[i])) used[exp[i] - 'a'] = 1;    }    for(i = 0; i < len && (i = exp.find("++", i)) != string::npos; ){        if(i + 2 < len && isalpha(exp[i+2]))            ++value[exp[i+2] - 'a'];        else            post[exp[i-1] - 'a'] = 1;        exp = exp.substr(0, i) + exp.substr(i + 2);    }    for(i = 0; i < len && (i = exp.find("--", i)) != string::npos; ){        if(i + 2 < len && isalpha(exp[i+2]))            --value[exp[i+2] - 'a'];        else            post[exp[i-1] - 'a'] = -1;        exp = exp.substr(0, i) + exp.substr(i + 2);    }//    cout << "exp = " << exp << "\n";}int eval(const string& exp, int res = 0){    if(exp.empty()) return res;    int i = 0;    bool add = true;    if(!isalpha(exp[i])){        add = exp[i] == '+';        ++i;    }    if(add) res += value[exp[i] - 'a'];    else res -= value[exp[i] - 'a'];    return eval(exp.substr(i+1), res);}void postEval(){    for(int i = 0; i < 26; ++i){        if(used[i]) cout << "    "                         << char('a' + i) << " = "                         << value[i] + post[i] << "\n";    }}int main(){    ios::sync_with_stdio(false);    string exp;    while(getline(cin, exp)){        cout << "Expression: " << exp << "\n";        preEval(exp);        cout << "    " << "value = " << eval(exp) << "\n";        postEval();    }    return 0;}

0 0
原创粉丝点击