#include < stack > #include < iostream > #include < string > #include < cstdio >
using namespace std;
struct Pri {
char op;
int pri;
}
lpri[4] = {
{‘ + ‘,
2
},
{‘ - ‘,
2
},
{‘ * ‘,
4
},
{‘ ^ ‘,
6
}
},
rpri[4] = {
{‘ + ‘,
1
},
{‘ - ‘,
1
},
{‘ * ‘,
3
},
{‘ ^ ‘,
5
}
};
int find_leftPri(char op) {
for (int i = 0; i < 4; i++) if (op == lpri[i].op) return lpri[i].pri;
}
int find_rightPri(char op) {
for (int i = 0; i < 4; i++) if (op == rpri[i].op) return rpri[i].pri;
}
int Precede(char op1, char op2) {
int L = find_leftPri(op1);
int R = find_rightPri(op2);
if (L == R) return 0;
if (L > R) return 1;
return - 1;
}
long long pow(int x, int n) {
long long ans = 1;
while (n--) ans *= x;
return ans;
}
long long Run(stack < long long > &num, char op) {
long long a = num.top();
num.pop();
long long b = num.top();
// cout<<"a="<<a<<" b="<<b<<" op is "<<op<<endl;
num.pop();
switch (op) {
case‘ + ‘: return b + a;
case‘ - ‘: return b - a;
case‘ * ‘: return b * a;
case‘ ^ ‘: return pow(b, a);
}
}
int main() {
string s;
int x;
while (scanf("%d", &x) != EOF) {
stack < char > op;
stack < long long > num;
int i,
j;
cin >> s;
for (i = 0; i < s.length(); i++) {
// cout<<"i="<<i<<endl;
if (s[i] >= ‘0‘ && s[i] <= ‘9‘) {
int t = 0;
for (j = i; s[j] >= ‘0‘ && s[j] <= ‘9‘; j++) t = t * 10 + (s[j] - ‘0‘);
num.push(t);
i = j - 1;
// cout<<"@@t="<<t<<" i="<<i<<" j="<<j<<endl;
} else if (s[i] == ‘X‘) {
int t = 0;
if ((s[i - 1] == ‘ - ‘ || s[i - 1] == ‘ + ‘) && i != 0) num.push(1);
if (!num.empty()) op.push(‘ * ‘);
num.push(x);
} else {
if ((s[i] == ‘ - ‘ || s[i] == ‘ + ‘) && num.empty()) {
// cout<<"......-x......."<<endl;
num.push(0);
}
if (op.empty()) op.push(s[i]);
else {
int judg = Precede(op.top(), s[i]);
switch (judg) {
long long t;
case 1:
t = Run(num, op.top());
num.push(t);
// cout<<"Run(num,op.top())="<<t<<endl;
op.pop();
i--;
break;
case - 1 : if ((s[i] == ‘ - ‘ || s[i] == ‘ + ‘) && s[i + 1] == ‘X‘) num.push(1);
op.push(s[i]);
break;
}
}
}
}
while (!op.empty()) {
num.push(Run(num, op.top()));
op.pop();
}
cout << num.top() << endl;
}
return 0;
}
来源: http://www.bubuko.com/infodetail-2288847.html