题解 - P1054 [NOIP 2005 提高组] 等价表达式

· · 题解

题目大意

给定一个带有变量 a 的题干表达式和 n 个同样带有变量 a 的选项表达式,求这 n 个选项表达式中哪些表达式和题干表达式的值相同。

解题思路

本题是一道经典的考察表达式计算的题目。

首先要明确,题目中的表达式都是中缀表达式。

那么就要知道什么是前缀表达式、中缀表达式、后缀表达式。

前缀表达式(Prefix)

表达式树的前缀遍历的结果。即对于整个表达式树的每个子树,按照根结点,左子树,右子树遍历出的结果。

中缀表达式(Infix)

表达式树的中缀遍历的结果。即对于整个表达式树的每个子树,按照左子树,根结点,右子树遍历出的结果(中缀表达式就是我们日常中写的表达式)。

后缀表达式(Suffix)

表达式树的后缀遍历的结果。即对于整个表达式树的每个子树,按照左子树,右子树,根结点遍历出的结果。

中缀表达式中会有括号,这就不太好处理了,但是后缀表达式是非常好计算的,因为后缀表达式不用考虑优先级,所以我们先把输入的中缀表达式转换成后缀表达式,再进行计算。

那么题目中的变量 a 怎么办呢,我们可以通过代入的方法解决。

那么代多少呢?首先 -1,0,1 是不可以用的,因为太特殊,所以我们只要代入一个其他的值就行了(这里我代入了 2)。

所以我们就可以先将题干表达式计算出结果,再对于每一个选项表达式也计算出结果,判断哪些相同即可。

实现过程

主函数

首先读题干字符串可以直接使用 getline。

然后需要用变量 num 来存它的值(计算函数这里叫 calc)。

getline(cin, infix);
num = calc();
cin >> n;

然后再读入每个选项字符串,需要注意,这里的换行都会多一个 \r,所以读入不能直接使用 getline,可以换成以下代码:

while (ch == '\n' || ch == '\r')
    ch = getchar();

while (ch != '\n' && ch != '\r') {
    if (ch != ' ')
        infix += ch;

    ch = getchar();
}

答案需要输出一个字符串,这里就用 string 的 ans 来存。

因为题目不保证字符串的括号合法,所以需要先判断一下是否合法,然后再判断当前的选项字符串的值是否等于 num,如果是就加入 ans,代码如下:

if (check() && calc() == num)
    ans += char('A' + i);

最后输出 ans 即可。

check 函数

可以用一个变量 tot 来记录当前还没有匹配的左括号的个数,每遇到一个右括号就减一,如果小于 0 就返回 false,最后如果 tot 还大于 0,就也返回 false,最后返回 true 即可,代码如下:

bool check() {
    int tot = 0;

    for (int i = 0; i < infix.size(); i ++ ) {
        if (infix[i] == '(')
            tot ++ ;

        if (infix[i] == ')') {
            tot -- ;

            if (tot < 0)
                return false;
        }
    }

    return !tot;
}

calc 函数

这里需要先把中缀表达式转成后缀表达式,这里我写了一个函数 infix_to_suffix,下面会详细讲。

这里转换后的后缀表达式我用了 vector 来存,那么后缀表达式如何求值呢?

我们可以定义一个数字栈,然后每遇到一个数字就扔到里面。

因为后缀表达式的 a + b 表示为 a b +,而且后缀表达式不用考虑优先级,所以每遇到一个符号,就弹出栈顶的两个数字,做完运算在扔回去,那么最后栈里省的值就是最后的值,代码如下:

(因为题目保证数字都是整数,所以这里符号就用负数表示了,-1 是加,-2 是减,-3 是乘,-4 是幂。还有一点需要注意就是数字可能过大,所以这里需要模上一个数,比如 10^9 + 7,然后幂运算用快速幂)

typedef long long LL;
const int mod = 1e9 + 7;

int quick_power(int a, int b, int p) {
    int res = 1, base = a;

    while (b) {
        if (b & 1)
        res = (LL)res * base % p;

        base = (LL)base * base % p;
        b >>= 1;
    }

    return res;
}

int calc() {
    infix_to_suffix();

    while (!st.empty())
        st.pop();

    for (auto item : suffix) {
        if (item > 0) {
            st.push(item);
            continue;
        }

        int b = st.top();
        st.pop();
        int a = st.top();
        st.pop();

        switch (item) {
            case -1:
                st.push((a + b) % mod);
                break;
            case -2:
                st.push((a - b) % mod);
                break;
            case -3:
                st.push((LL)a * b % mod);
                break;
            case -4:
                st.push(quick_power(a, b, mod));
                break;
        }
    }

    return st.top();
}

infix_to_suffix 函数

这里就是中缀转后缀,那么具体的方法如下:

因为在表达式树上的数字都是叶子结点,所以数字的顺序不用变,所以遇到一个数字(或者 a,那就算 2)就直接放到 suffix 里面就行。

数字有可能不只一位,所以需要一些处理,即

if (isdigit(infix[i])) {
    digit = digit * 10 + infix[i] - 48;
    continue;
}

这里的 isdigit 函数是 cctype 库里的函数,用来判断字符是否是数字。

接下来处理符号。

这里就涉及到中缀表达式中的优先级问题了。

首先需要一个符号栈(ops)。

然后如果是左括号,就直接往栈里压 0:

if (infix[i] == '(') {
    ops.push(0);
    continue;
}

如果是右括号,就把直到左括号(0)的所有符号都弹到 suffix 里(注意要把左括号也弹掉):

if (infix[i] == ')') {
    while (ops.top() != 0) {
        suffix.push_back(ops.top());
        ops.pop();
    }

    ops.pop();
    continue;
}

然后就是加减乘幂了,这里就是把所有优先级大于当前符号的都弹到 suffix 里,最后把自己压进去就行了,不细讲了:

if (infix[i] == '+') {
  while (!ops.empty() && ops.top() < 0) {
      suffix.push_back(ops.top());
      ops.pop();
  }

  ops.push(-1);
  continue;
}

if (infix[i] == '-') {
  while (!ops.empty() && ops.top() < 0) {
      suffix.push_back(ops.top());
      ops.pop();
  }

  ops.push(-2);
  continue;
}

if (infix[i] == '*') {
  while (!ops.empty() && ops.top() < -2) {
      suffix.push_back(ops.top());
      ops.pop();
  }

  ops.push(-3);
  continue;
}

if (infix[i] == '^') {
  while (!ops.empty() && ops.top() < -3) {
      suffix.push_back(ops.top());
      ops.pop();
  }

  ops.push(-4);
  continue;
}

最后再把最后那个数字(或 a)和剩下的符号压到 suffix 里即可:

if (digit)
    suffix.push_back(digit);

while (!ops.empty()) {
    suffix.push_back(ops.top());
    ops.pop();
}

整体代码

不懂的具体就看代码吧:

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <cctype>
using namespace std;

typedef long long LL;
const int mod = 1e9 + 7;

string infix;
vector <int> suffix;
stack <int> ops;
stack <int> st;
int n;
int num;
string ans;

int quick_power(int a, int b, int p) {
    int res = 1, base = a;

    while (b) {
        if (b & 1)
        res = (LL)res * base % p;

        base = (LL)base * base % p;
        b >>= 1;
    }

    return res;
}

bool check() {
    int tot = 0;

    for (int i = 0; i < infix.size(); i ++ ) {
        if (infix[i] == '(')
            tot ++ ;

        if (infix[i] == ')') {
            tot -- ;

            if (tot < 0)
                return false;
        }
    }

    return !tot;
}

void infix_to_suffix() {
    int digit = 0;
    suffix.clear();

    for (int i = 0; i < infix.size(); i ++ ) {
        if (isdigit(infix[i])) {
            digit = digit * 10 + infix[i] - 48;
            continue;
        }

        if (infix[i] == 'a')
            suffix.push_back(2);
        else if (digit) {
            suffix.push_back(digit);
            digit = 0;
        }

        if (infix[i] == '(') {
            ops.push(0);
            continue;
        }

        if (infix[i] == ')') {
            while (ops.top() != 0) {
                suffix.push_back(ops.top());
                ops.pop();
            }

            ops.pop();
            continue;
        }

        if (infix[i] == '+') {
            while (!ops.empty() && ops.top() < 0) {
                suffix.push_back(ops.top());
                ops.pop();
            }

            ops.push(-1);
            continue;
        }

        if (infix[i] == '-') {
            while (!ops.empty() && ops.top() < 0) {
                suffix.push_back(ops.top());
                ops.pop();
            }

            ops.push(-2);
            continue;
        }

        if (infix[i] == '*') {
            while (!ops.empty() && ops.top() < -2) {
                suffix.push_back(ops.top());
                ops.pop();
            }

            ops.push(-3);
            continue;
        }

        if (infix[i] == '^') {
            while (!ops.empty() && ops.top() < -3) {
                suffix.push_back(ops.top());
                ops.pop();
            }

            ops.push(-4);
            continue;
        }
    }

    if (digit)
        suffix.push_back(digit);

    while (!ops.empty()) {
        suffix.push_back(ops.top());
        ops.pop();
    }
}

int calc() {
    infix_to_suffix();

    while (!st.empty())
        st.pop();

    for (auto item : suffix) {
        if (item > 0) {
            st.push(item);
            continue;
        }

        int b = st.top();
        st.pop();
        int a = st.top();
        st.pop();

        switch (item) {
            case -1:
                st.push((a + b) % mod);
                break;
            case -2:
                st.push((a - b) % mod);
                break;
            case -3:
                st.push((LL)a * b % mod);
                break;
            case -4:
                st.push(quick_power(a, b, mod));
                break;
        }
    }

    return st.top();
}

int main() {
    getline(cin, infix);
    num = calc();
    cin >> n;

    for (int i = 0; i < n; i ++ ) {
        char ch = getchar();
        infix = "";

        while (ch == '\n' || ch == '\r')
            ch = getchar();

        while (ch != '\n' && ch != '\r') {
            if (ch != ' ')
                infix += ch;

            ch = getchar();
        }

        if (check() && calc() == num)
            ans += char('A' + i);
    }

    cout << ans << endl;

    return 0;
}

完结撒花!