问相同代码概率 RE 的原因
查看原帖
问相同代码概率 RE 的原因
446979
masonxiong楼主2025/6/12 16:34

以下这份代码一定会 RE on #3 #4,但是不一定 RE on #1。

很好奇为什么同样的代码会得出这样的两种结果。

#include <bits/stdc++.h>

constexpr int Maxq = 2e5 + 5, Maxv = 2e5 + 5;

int q, v, x, y;
std::vector<std::pair<int, int>> items;
std::array<std::vector<int>, Maxq> tree;
std::stack<int, std::vector<int>> stack;
std::array<int, Maxq> id, size, answer, child;
std::array<std::array<int, Maxv>, 32> F;

void firstDFS(int current, int previous) {
    size[current] = 1;
    for (int next : tree[current]) {
        if (next != previous) {
            firstDFS(next, current);
            size[current] += size[next];
            if (size[next] > size[child[current]])
                child[current] = next;
        }
    }
}

void secondDFS(int current, int previous, int carray, int parray) {
    auto item = items[current - 1];
    for (int i = 0; i <= v; i++) {
        F[carray][i] = F[parray][i];
        if (i >= item.first)
            F[carray][i] = std::max(F[carray][i], F[carray][i - item.first] + item.second);
        answer[current] = std::max(answer[current], F[carray][i]);
    }
    for (int next : tree[current])
        if (next != child[current])
            secondDFS(next, current, carray + 1, carray);
    if (child[current])
        secondDFS(child[current], current, carray, carray);
}

int main() {
    std::cin.tie(nullptr)->sync_with_stdio(false);
    std::cin >> q >> v;
    for (int i = 0; i < q; i++) {
        std::string o;
        if (std::cin >> o, o == "erase") {
            stack.pop();
        } else if (o == "add") {
            std::cin >> x >> y;
            items.emplace_back(x, y);
            if (!stack.empty())
                tree[stack.top()].push_back(items.size());
            stack.push(items.size());
        }
        if (!stack.empty())
            id[i] = stack.top();
    }
    for (int i = 1; i <= q; i++) {
        if (!size[i]) {
            firstDFS(i, i);
            secondDFS(i, i, 1, 0);
        }
    }
    for (int i = 0; i < q; i++)
        std::cout << answer[id[i]] << '\n';
    return 0;
}
2025/6/12 16:34
加载中...