题解:P8997 [CEOI 2022] Homework

· · 题解

简单题,绿黄!

首先注意到这个式子很连续,猜测答案一定是一个连续段。

我们先不急着证明。

这种题显然要建表达式树。我们观察到了子问题……只不过对于一个包含 k 个 \texttt ? 的子树,我们是从 1\sim n 中选择 k 个数字并排列,而不是从 1\sim k 中排列。

不过这也是好处理的,因为我们可以在合并两个子问题的时候把两边的值穿插起来。所以还是只需要考虑 1\sim k,这就是和原问题形式完全相同的子问题了。

若是叶子节点(即 \texttt ?,不过我的代码中的叶子节点其实是 \max(\texttt ?,\texttt ?) 或 \min(\texttt ?,\texttt ?),但都不重要),则显然答案为 [1,1]。若是非叶子呢?我们假设左子树大小为 s_1(共有 s_1 个 \texttt ?),区间为 [i_1,a_1],右树点大小为 s_2,答案区间为 [i_2,a_2]。

分类讨论这个节点是 \min 还是 \max:

建表达式树用栈维护右链即可。时间复杂度 O(n)。

:::info[关于证明]

我们考虑上面 DP 的过程,数学归纳法即可证明答案是连续段。

:::

:::info[rec&code]

rec。

#include <stack>
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>

using namespace std;

const auto U = [](auto x) { return [x](auto ...y) { return x(x, y...); }; };

class node
{
public:
    char tp;
    int l, r;
} nodes[2000005];
int sz[2000005];
int minn[2000005], maxn[2000005];

int main()
{
    string str;
    cin >> str;
    int cur = 0;
    stack<int> stk;
    bool im;
    for(char ch : str)
    {
        if(ch == 'a') im = true;
        else if(ch == 'i') im = false;
        if(ch == '(')
        {
            nodes[++cur] = {im ? 'a' : 'i', 0, 0};
            if(!stk.empty()) (nodes[stk.top()].l ? nodes[stk.top()].r : nodes[stk.top()].l) = cur;
            stk.push(cur);
        }
        if(ch == ')') stk.pop();
        if(ch == '?') (nodes[stk.top()].l ? nodes[stk.top()].r : nodes[stk.top()].l) = -1;
    }
    U([&](auto &&self, int x) -> void
    {
        if(nodes[x].l > 0) self(self, nodes[x].l);
        if(nodes[x].r > 0) self(self, nodes[x].r);
        int lmin = (nodes[x].l > 0 ? minn[nodes[x].l] : 1), lmax = (nodes[x].l > 0 ? maxn[nodes[x].l] : 1), rmin = (nodes[x].r > 0 ? minn[nodes[x].r] : 1), rmax = (nodes[x].r > 0 ? maxn[nodes[x].r] : 1);
        int lsz = (nodes[x].l > 0 ? sz[nodes[x].l] : 1);
        int rsz = (nodes[x].r > 0 ? sz[nodes[x].r] : 1);
        sz[x] = lsz + rsz;
        if(nodes[x].tp == 'a') // max
        {
            maxn[x] = max(lmax + rsz, rmax + lsz);
            minn[x] = lmin + rmin;
        }
        else
        {
            minn[x] = min(lmin, rmin);
            maxn[x] = lmax + rmax - 1;
        }
        // printf("%d: [%d, %d]\n", x, minn[x], maxn[x]);
    })(1);
    printf("%d\n", maxn[1] - minn[1] + 1);
    return 0;
}

:::