表达式求值1
题目信息
见题目链接
解题方法
由题干可以得出,对于1位2进制,有
运算符 | 运算规则 | 运算优先级 |
---|---|---|
⊕ \oplus ⊕ | 0 ⊕ 0 = 0 0 ⊕ 1 = 1 1 ⊕ 0 = 1 1 ⊕ 1 = 1 0 \oplus 0=0 \\ 0 \oplus 1=1 \\ 1 \oplus 0=1 \\ 1 \oplus 1=1 0⊕0=00⊕1=11⊕0=11⊕1=1 | 低 |
× \times × | 0 × 0 = 0 0 × 1 = 1 1 × 0 = 1 1 × 1 = 1 0 \times 0=0 \\ 0 \times 1=1 \\ 1 \times 0=1 \\ 1 \times 1=1 0×0=00×1=11×0=11×1=1 | 高 |
( ) () () | ( 表达式 ) (\operatorname{表达式}) (表达式) | 最高 |
那么就联想到用栈(stack)来对表达式进行存储。
栈储存方法:以优先级顺序把表达式压入栈中。再一个个算。
#include <bits/stdc++.h>//万能头
const int M = 10007, N = 100005;
int n, u[N], v[N], top, k;
char c[N], st[N], ans[2 * N];
int main() {
scanf("%d\n%s", &n, c);
ans[++k] = '.';//结束符
for (int i = 0; c[i]; i++) {
if (c[i] == '(' || c[i] == '*')
st[++top] = c[i];
if (c[i] == '+') {
while (st[top] == '*')
ans[++k] = st[top--];
st[++top] = c[i];
}
if (c[i] == ')') {
while (st[top] != '(')
ans[++k] = st[top--];
top--;
}
if (c[i] != '(' && c[i] != ')')
ans[++k] = '.';
}
while (top > 0)
ans[++k] = st[top--];
for (int i = 1; i <= k; i++) {
if (ans[i] == '.') {
u[++top] = 1;
v[top] = 1;
}
if (ans[i] == '*') {
top--;
u[top] = (u[top + 1] * v[top] + u[top] * v[top + 1] + u[top] * u[top + 1]) % M;
v[top] = v[top] * v[top + 1] % M;
}
if (ans[i] == '+') {
top--;
v[top] = (u[top + 1] * v[top] + u[top] * v[top + 1] + v[top] * v[top + 1]) % M;
u[top] = u[top] * u[top + 1] % M;
}
}
printf("%d", u[1]);
return 0;
}
2011年NOIP普及组第4题 ↩︎