老师讲了就很简单,不需要用什么栈:#include <bits/stdc++.h>
using namespace std;
const int N = 1000100;
int x, n;
char s[N];
int c1[N], c2[N], l1[N], l2[N], cor, cand;
#define p 1000000007
int calc(int l, int r) {
if (l1[r] >= l) {
if (s[l1[r]] == '+')
return (calc(l, l1[r] - 1) + calc(l1[r] + 1, r)) % p;
else return (calc(l, l1[r] - 1) - calc(l1[r] + 1, r) + p) % p;
} else if (l2[r] >= l) {
if (s[l1[r]] == '*')
return (1LL * calc(l, l1[r] - 1) * calc(l1[r] + 1, r)) % p;
else return (calc(l, l1[r] - 1) / calc(l1[r] + 1, r));
}
if (s[l] == '(' && s[r] == ')') return calc(l + 1, r - 1);
int res = 0;
for (int i = l; i <= r; ++i)
res = res * 10 + s[i] - '0';
return res % p;
}
int main() {
scanf("%s", s + 1);
n = strlen(s + 1);
for (int i = 1; i <= n; ++i) {
if (s[i] == '(') ++x;
else if (s[i] == ')') --x;
if (s[i] == '*' || s[i] == '/') c2[x] = i;
else if (s[i] == '+' || s[i] == '-') c1[x] = i;
l1[i] = c1[x];
l2[i] = c2[x];
}
int ans = calc(1, n);
printf("%d\n", ans);
return 0;
}
|