跳到正文

题解

题解:P11855 [CSP-J2022 山东] 部署

lkrqwq约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
获赞
1
题目
P11855

版本

  1. v1当前

我们发现,对于操作 11,等价于根据 dfn 序进行差分,操作二相当于对每一对 (x,v)(x, v) 互相加 yy,那么直接 dfs 求个 dfn 序就做完了,时间复杂度 O(n)O(n)。

代码如下:

C++
int main() {
#if MULTI_TEST == 1
    LL T;
    std::cin >> T;
    while (T--) {
        // Test cases...
    }
#else
    int n;
    cin >> n;
    std::vector<VI> adj(n + 1);
    VLL a(n + 1);
    for (int i = 1; i <= n; ++i)
        cin >> a[i];
    std::vector<PII> e;
    for (int i = 1, x, y; i < n; ++i)
        cin >> x >> y, e.eb(x, y), adj[x].eb(y), adj[y].eb(x);
    int cnt = 0;
    VI l(n + 1, 0), r(n + 1, 0), rev(n + 1, 0);
    auto Dfs = [&](auto&& self, int x, int p) -> void {
        rev[l[x] = ++cnt] = x;
        for (auto& y : adj[x]) {
            if (y == p) continue;
            self(self, y, x);
        }
        r[x] = cnt;
        };
    Dfs(Dfs, 1, 0);
    VLL d(cnt + 2, 0), t(n + 1, 0);
    int m;
    cin >> m;
    while (m--) {
        int tp, x, y;
        cin >> tp >> x >> y;
        if (tp == 1) {
            d[l[x]] += y;
            d[r[x] + 1] -= y;
        }
        else {
            t[x] += y;
        }
    }
    VLL t1(n + 1, 0), t2(n + 1, 0);
    for (int i = 1; i <= cnt; ++i) {
        t1[rev[i]] = (d[i] += d[i - 1]);
        t2[i] = t[i];
    }
    for (auto& [u, v] : e) t2[u] += t[v], t2[v] += t[u];
    int q, x;
    cin >> q;
    while (q--) {
        cin >> x;
        cout << a[x] + t1[x] + t2[x] << "\n";
    }
#endif
    return 0;
}
原文