1 solutions

  • 0
    @ 2026-8-21 9:26:39

    1. 题目概述

    给定一棵以 11 为根的带权树。节点 ii 具有颜色 cic_i 和数值 aia_i,颜色 cc 具有权值 wcw_c。

    同色节点 u,vu,v 的同步代价为

    D(u,v)=∣au−av∣+dist⁡(u,v).D(u,v)=|a_u-a_v|+\operatorname{dist}(u,v).

    询问 (x,K)(x,K) 要求计算:有多少种颜色能够在 subtree⁡(x)\operatorname{subtree}(x) 内找到同步代价不超过 KK 的同色点对,并对这些颜色的 wcw_c 求和。

    这道题的直接对象是同色点对。若一种颜色出现 ss 次,点对数量可以达到 Θ(s2)\Theta(s^2);所有颜色合计最坏为 Θ(n2)\Theta(n^2)。正解包含两次压缩:

    1. 把所有同色点对压缩成 O(n)O(n) 个“LCA 事件”;
    2. 按事件代价扫描时,把一种颜色对所有祖先的重复贡献压缩成每次只新增一条链。

    最终复杂度为

    O((n+q)log⁡2n)\boxed{O((n+q)\log^2 n)}

    的期望时间,空间复杂度为 O(n+q)O(n+q)。

    2. 第一次转化:把点对放到它们的 LCA 上

    固定颜色 cc 和节点 zz,定义

    $$g(c,z)= \min_{\substack{u\ne v\\c_u=c_v=c\\\operatorname{lca}(u,v)=z}} D(u,v).$$

    若不存在合法点对,令 g(c,z)=+∞g(c,z)=+\infty。

    对每个有限的 g(c,z)g(c,z),建立一个三元组

    (c,z,g(c,z)),(c,z,g(c,z)),

    称为一个事件。事件只是题解中的中间对象,题面中并未显式给出。

    引理 1

    颜色 cc 在 subtree⁡(x)\operatorname{subtree}(x) 中存在同步代价不超过 KK 的点对,当且仅当存在

    z∈subtree⁡(x)z\in\operatorname{subtree}(x)

    满足

    g(c,z)≤K.g(c,z)\le K.

    证明

    若存在同色点对 u,v∈subtree⁡(x)u,v\in\operatorname{subtree}(x) 且 D(u,v)≤KD(u,v)\le K,令

    z=lca⁡(u,v).z=\operatorname{lca}(u,v).

    因为一棵根树的子树对 LCA 封闭,所以 z∈subtree⁡(x)z\in\operatorname{subtree}(x),并且

    g(c,z)≤D(u,v)≤K.g(c,z)\le D(u,v)\le K.

    反过来,若 z∈subtree⁡(x)z\in\operatorname{subtree}(x) 且 g(c,z)≤Kg(c,z)\le K,根据定义存在同色节点 u,vu,v,满足 lca⁡(u,v)=z\operatorname{lca}(u,v)=z 且 D(u,v)=g(c,z)D(u,v)=g(c,z)。二者都是 zz 的后代,因而也都属于 subtree⁡(x)\operatorname{subtree}(x)。证毕。

    因此,原询问变成:

    对每个颜色,判断其是否在查询子树中存在一个代价不超过 KK 的事件;若存在,只计算一次该颜色的权值。

    3. 为什么事件总数只有 O(n)O(n)

    固定一种颜色 cc,设它出现于节点集合

    Sc={v1,v2,…,vs}.S_c=\{v_1,v_2,\ldots,v_s\}.

    所有可能产生有限 g(c,z)g(c,z) 的节点 zz 都是某两个 ScS_c 中节点的 LCA。

    对 ScS_c 构造虚树:取所有原节点以及按 DFS 序相邻节点的 LCA,再按 DFS 序排序并连接祖先关系。标准虚树性质说明,虚树节点数不超过

    2s−1.2s-1.

    而任意两个 ScS_c 中节点的 LCA 都属于这棵虚树。因此颜色 cc 最多产生 O(s)O(s) 个事件。

    对所有颜色求和:

    ∑cO(∣Sc∣)=O(n).\sum_c O(|S_c|)=O(n).

    这一步把潜在的 Θ(n2)\Theta(n^2) 个点对压缩成了 O(n)O(n) 个节点事件。

    4. 在一棵颜色虚树上计算所有 g(c,z)g(c,z)

    下面固定一种颜色 cc,只讨论它的虚树。

    4.1 按 LCA 精确分组

    设虚树节点为 zz,它的虚树儿子为

    v1,v2,…,vk.v_1,v_2,\ldots,v_k.

    把颜色 cc 的原节点分成以下若干组:

    • 若 zz 本身颜色为 cc,则 {z}\{z\} 是一个单独的组;
    • 每个虚树儿子 viv_i 的虚树子树中的原节点构成一个组。

    两个颜色为 cc 的节点的 LCA 恰好为 zz,当且仅当它们来自不同组。

    因此,g(c,z)g(c,z) 就是不同组之间的最小同步代价。

    4.2 把同步代价写成一维绝对值查询

    在处理节点 zz 时,对其后代原节点 uu 记录二元组

    (au,du),du=dist⁡(z,u).(a_u,d_u), \qquad d_u=\operatorname{dist}(z,u).

    若 u,vu,v 来自不同组,则 lca⁡(u,v)=z\operatorname{lca}(u,v)=z,于是

    dist⁡(u,v)=du+dv.\operatorname{dist}(u,v)=d_u+d_v.

    同步代价为

    D(u,v)=du+dv+∣au−av∣.D(u,v)=d_u+d_v+|a_u-a_v|.

    现在考虑一个待查询点

    p=(A,D)p=(A,D)

    和集合中的点

    q=(a,d).q=(a,d).

    若 a≤Aa\le A,则

    D+d+∣A−a∣=D+A+(d−a).D+d+|A-a|=D+A+(d-a).

    所以在所有 a≤Aa\le A 的点中,只需知道

    min⁡(d−a).\min(d-a).

    若 a≥Aa\ge A,则

    D+d+∣A−a∣=D−A+(d+a),D+d+|A-a|=D-A+(d+a),

    只需知道

    min⁡(d+a).\min(d+a).

    因此查询公式为

    $$\boxed{ D+\min\left( A+\min_{a\le A}(d-a), -A+\min_{a\ge A}(d+a) \right) }.$$

    这里出现了题目的第一层隐藏支配关系:

    • 在 AA 左侧,除了使 d−ad-a 最小的点,其余点对当前查询永远不会更优;
    • 在 AA 右侧,除了使 d+ad+a 最小的点,其余点也不会更优。

    4.3 数据结构

    使用按键 (au,u)(a_u,u) 排序的随机 Treap。使用节点编号作为第二关键字,可以自然保留相同 aa 的不同节点。

    每个 Treap 节点维护:

    • 子树大小;
    • 子树内的 min⁡(d−a)\min(d-a);
    • 子树内的 min⁡(d+a)\min(d+a);
    • 整棵子树的距离加法标记。

    支持:

    1. 插入一个点 (a,d)(a,d);
    2. 查询给定 (A,D)(A,D) 与集合中任意点的最小代价;
    3. 对集合中所有 dd 加同一个数;
    4. 枚举整棵 Treap 的节点,用于启发式合并。

    当把虚树儿子 vv 的数据结构提升到父亲 zz 时,所有点到当前根的距离统一增加

    dist⁡(z,v),\operatorname{dist}(z,v),

    因此只需给 Treap 打一次整体加标记。

    4.4 启发式合并

    在虚树节点 zz,依次合并各个组。

    设已经合并的组对应集合 AA,新组对应集合 BB:

    1. 先枚举较小集合中的每个点,在较大集合中查询最优匹配,用于更新 g(c,z)g(c,z);
    2. 查询全部完成后,再把较小集合中的点插入较大集合。

    必须“先全部查询,再插入”,否则会错误地把同一个新组内部的点对计入当前节点,而这些点对的 LCA 应当位于更深的位置。

    每次总是把较小集合搬入较大集合。一个原节点每被搬运一次,它所在集合的大小至少翻倍,所以每个点最多被搬运 O(log⁡n)O(\log n) 次。每次查询和插入为 O(log⁡n)O(\log n),全部颜色的总复杂度为

    O(nlog⁡2n).O(n\log^2 n).

    引理 2

    上述虚树合并算法得到的 best[z] 恰好等于 g(c,z)g(c,z)。

    证明

    根据分组方式,LCA 为 zz 的点对恰好是来自不同组的点对。

    算法每次把一个完整的新组与之前所有组的并进行匹配,因此:

    • 任意两个不同组之间的点对都会在较晚加入的那个组被合并时被考察;
    • 同一组内部的点对从不会在当前节点被考察;
    • Treap 查询公式精确返回一个点与另一个集合之间的最小 du+dv+∣au−av∣d_u+d_v+|a_u-a_v|。

    所以算法取到的最小值恰好是所有 LCA 为 zz 的同色点对的最小同步代价。证毕。

    5. 第二次转化:按代价扫描事件

    现在已经得到至多 O(n)O(n) 个事件

    (c,z,g).(c,z,g).

    将事件按 gg 从小到大排序,将询问按 KK 从小到大排序。

    扫描到阈值 KK 时,激活全部满足

    g≤Kg\le K

    的事件。

    对颜色 cc,记当前激活事件节点集合为 ScS_c。根据引理 1,颜色 cc 对询问节点 xx 有贡献,当且仅当

    Sc∩subtree⁡(x)≠∅.S_c\cap\operatorname{subtree}(x)\ne\varnothing.

    等价地,存在 z∈Scz\in S_c,使得 xx 是 zz 的祖先。

    所以颜色 cc 应当给节点集合

    Uc=⋃z∈ScP(1,z)U_c=\bigcup_{z\in S_c}P(1,z)

    中的每个节点贡献 wcw_c。

    关键问题变成:动态向 ScS_c 插入节点,并维护根路径并集 UcU_c。

    6. 插入一个事件节点只会新增一条链

    向 ScS_c 插入新节点 zz。

    旧的 UcU_c 是若干根路径的并,因此对祖先封闭。它与 P(1,z)P(1,z) 的交一定是一个根前缀

    P(1,h).P(1,h).

    于是新增加的部分一定是一条连续链:

    P(t,z),P(t,z),

    其中 tt 是 hh 到 zz 方向上的下一个节点;若旧集合为空,则整条 P(1,z)P(1,z) 都是新增部分。

    剩下的问题是快速求出最深的已覆盖祖先 hh。

    对任意已有事件节点 y∈Scy\in S_c,根路径 P(1,y)P(1,y) 与 P(1,z)P(1,z) 的交为

    P(1,lca⁡(z,y)).P(1,\operatorname{lca}(z,y)).

    因此

    $$h=\arg\max_{y\in S_c} \operatorname{dep}(\operatorname{lca}(z,y)).$$

    7. Euler 序前驱后继性质

    对每种颜色,用有序集合维护所有激活事件节点的 DFS 进入时间 tin⁡\operatorname{tin}。

    设 p,sp,s 分别为 zz 在集合中的前驱和后继(若存在)。有:

    引理 3

    $$\max_{y\in S_c} \operatorname{dep}(\operatorname{lca}(z,y))$$

    一定由 pp 或 ss 取得。

    证明

    只考虑 DFS 序位于 zz 左侧的已有节点。设其中某个节点为 yy,并令

    h=lca⁡(z,y).h=\operatorname{lca}(z,y).

    z,yz,y 都在 subtree⁡(h)\operatorname{subtree}(h) 中,而子树在 DFS 序上是连续区间。因此,任何 DFS 序位于 yy 与 zz 之间的节点也都在 subtree⁡(h)\operatorname{subtree}(h) 中。

    左侧最靠近 zz 的已有节点正是前驱 pp,所以 p∈subtree⁡(h)p\in\operatorname{subtree}(h),从而

    lca⁡(z,p)\operatorname{lca}(z,p)

    不可能比 hh 更浅。

    右侧完全对称,由后继 ss 覆盖。故全局最深 LCA 一定由前驱或后继取得。证毕。

    于是每次插入只需:

    1. 在该颜色的 DFS 序集合中找前驱、后继;
    2. 各做一次 LCA;
    3. 取更深者作为 hh;
    4. 若 h=zh=z,说明 zz 已被旧并集覆盖,无需更新;
    5. 否则找到 hh 到 zz 路径上的第一个节点 tt,对 P(t,z)P(t,z) 加 wcw_c。

    8. 全局维护:树链剖分 + Fenwick 树

    扫描过程中需要支持:

    • 对一条树上路径加一个数;
    • 查询单个节点当前累计值。

    所有新增路径均为祖先到后代的路径,但使用普通树链剖分即可。

    一条路径被拆成 O(log⁡n)O(\log n) 个重链区间。对每个 DFS 位置区间执行区间加,使用 Fenwick 树的差分形式:

    • 在 ll 加 vv;
    • 在 r+1r+1 加 −v-v;
    • 单点值为前缀和。

    一次事件激活复杂度为

    O(log⁡2n),O(\log^2 n),

    一次询问只需在节点 xx 的重剖位置执行一次 Fenwick 前缀查询,复杂度为

    O(log⁡n).O(\log n).

    9. 完整正确性证明

    定理

    算法对每次询问输出的值等于题目要求的答案。

    证明

    固定询问 (x,K)(x,K)。

    事件按代价扫描后,当前被激活的事件恰好是所有满足 g(c,z)≤Kg(c,z)\le K 的事件。

    对任意颜色 cc:

    • 根据引理 1,cc 在 subtree⁡(x)\operatorname{subtree}(x) 内存在合法点对,当且仅当存在激活事件节点 z∈subtree⁡(x)z\in\operatorname{subtree}(x);
    • 这又等价于 xx 是某个 z∈Scz\in S_c 的祖先;
    • 也等价于 x∈Uc=⋃z∈ScP(1,z)x\in U_c=\bigcup_{z\in S_c}P(1,z)。

    扫描维护过程中,每次插入事件节点时只给 UcU_c 中此前未覆盖的链加上 wcw_c。因此:

    • 若 x∉Ucx\notin U_c,颜色 cc 对 xx 的累计贡献为 00;
    • 若 x∈Ucx\in U_c,颜色 cc 恰好贡献一次 wcw_c,不会因多个事件重复计算。

    对所有颜色求和后,节点 xx 当前维护值正好是题目答案。证毕。

    10. 复杂度分析

    设颜色 cc 出现 scs_c 次。

    • 每种颜色的虚树大小为 O(sc)O(s_c),所有颜色虚树总大小为 O(n)O(n);
    • 虚树构造的总排序复杂度为 O(nlog⁡n)O(n\log n);
    • 启发式合并中每个原节点被搬运 O(log⁡n)O(\log n) 次,每次查询和插入 O(log⁡n)O(\log n),共 O(nlog⁡2n)O(n\log^2 n);
    • 事件数量为 O(n)O(n);
    • 每个事件执行有序集合操作、LCA 和一次路径加,共 O(log⁡2n)O(\log^2 n);
    • 每个询问为 O(log⁡n)O(\log n)。

    因此总期望时间复杂度为

    O(nlog⁡2n+qlog⁡n),\boxed{O(n\log^2 n+q\log n)},

    也可统一写作

    O((n+q)log⁡2n).\boxed{O((n+q)\log^2 n)}.

    空间复杂度为

    O(n+q).\boxed{O(n+q)}.

    “期望”来自实现中用于虚树集合合并的随机 Treap。

    11. 实现细节与易错点

    1. 相同的 aia_i 必须保留多个节点。 参考实现以 (ai,i)(a_i,i) 作为 Treap 键,避免错误去重。
    2. 新组必须先查询、后插入。 否则同一组内部点对会被错误计入当前虚树节点。
    3. 虚树边长不是原树单边权。 应使用$$\operatorname{distRoot}(v)-\operatorname{distRoot}(z).$$
    4. 同一阈值下先激活事件,再回答询问。 因为条件是 g≤Kg\le K。
    5. 某颜色首次激活事件时,应对整条 P(1,z)P(1,z) 加 wcw_c。
    6. 若最深 LCA 为 zz,说明已有激活事件位于 zz 的子树中,zz 本身已经被覆盖,不应重复加。
    7. 参考代码全部使用迭代 DFS 和迭代重链编号,避免链形树导致递归栈溢出;Treap 递归深度为期望 O(log⁡n)O(\log n)。
    8. 距离、阈值、答案均使用 long long。

    12. 对拍说明

    附带:

    • solution.cpp:满分算法;
    • brute.cpp:小数据平方级暴力;
    • stress.py:随机对拍脚本;
    • stress_targeted.py:将查询阈值集中在真实点对代价的 D−1,D,D+1D-1,D,D+1 附近,专门检查边界。

    本交付版本已通过:

    • 1500 组普通随机对拍;
    • 300 组阈值边界强化对拍;
    • 100 组 AddressSanitizer / UndefinedBehaviorSanitizer 随机测试;
    • n=105,q=2×105n=10^5,q=2\times10^5 的规模性能测试。

    13. 参考代码

    下面代码与单独提供的 solution.cpp 完全一致。

    #include <bits/stdc++.h>
    using namespace std;
    
    using int64 = long long;
    
    static constexpr int64 INF64 = (int64)4e18;
    
    struct Edge {
        int to;
        int64 w;
    };
    
    struct Fenwick {
        int n = 0;
        vector<int64> bit;
    
        explicit Fenwick(int n_ = 0) { init(n_); }
    
        void init(int n_) {
            n = n_;
            bit.assign(n + 2, 0);
        }
    
        void add(int x, int64 v) {
            for (int i = x; i <= n; i += i & -i) bit[i] += v;
        }
    
        void range_add(int l, int r, int64 v) {
            if (l > r) return;
            add(l, v);
            if (r + 1 <= n) add(r + 1, -v);
        }
    
        int64 point_query(int x) const {
            int64 res = 0;
            for (int i = x; i > 0; i -= i & -i) res += bit[i];
            return res;
        }
    };
    
    struct TreapNode {
        TreapNode *l = nullptr, *r = nullptr;
        uint64_t pri = 0;
        int sz = 1;
        int id = 0;
        int64 a = 0;
        int64 d = 0;
        int64 mn_minus = 0;
        int64 mn_plus = 0;
        int64 lazy = 0;
    };
    
    struct TreapPool {
        vector<TreapNode> pool;
        int ptr = 0;
        uint64_t seed = 0x9e3779b97f4a7c15ULL;
    
        explicit TreapPool(int capacity = 0) : pool(capacity + 5) {}
    
        uint64_t rng() {
            seed += 0x9e3779b97f4a7c15ULL;
            uint64_t z = seed;
            z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
            z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
            return z ^ (z >> 31);
        }
    
        TreapNode* make_node(int id, int64 a, int64 d) {
            TreapNode *t = &pool[++ptr];
            t->l = t->r = nullptr;
            t->pri = rng();
            t->sz = 1;
            t->id = id;
            t->a = a;
            t->d = d;
            t->mn_minus = d - a;
            t->mn_plus = d + a;
            t->lazy = 0;
            return t;
        }
    };
    
    static inline int treap_size(TreapNode *t) {
        return t ? t->sz : 0;
    }
    
    static inline void treap_apply(TreapNode *t, int64 delta) {
        if (!t) return;
        t->d += delta;
        t->mn_minus += delta;
        t->mn_plus += delta;
        t->lazy += delta;
    }
    
    static inline void treap_push(TreapNode *t) {
        if (!t || t->lazy == 0) return;
        treap_apply(t->l, t->lazy);
        treap_apply(t->r, t->lazy);
        t->lazy = 0;
    }
    
    static inline void treap_pull(TreapNode *t) {
        t->sz = 1 + treap_size(t->l) + treap_size(t->r);
        t->mn_minus = t->d - t->a;
        t->mn_plus = t->d + t->a;
        if (t->l) {
            t->mn_minus = min(t->mn_minus, t->l->mn_minus);
            t->mn_plus = min(t->mn_plus, t->l->mn_plus);
        }
        if (t->r) {
            t->mn_minus = min(t->mn_minus, t->r->mn_minus);
            t->mn_plus = min(t->mn_plus, t->r->mn_plus);
        }
    }
    
    static inline bool treap_less(const TreapNode *x, const TreapNode *y) {
        if (x->a != y->a) return x->a < y->a;
        return x->id < y->id;
    }
    
    TreapNode* rotate_right(TreapNode *y) {
        treap_push(y);
        TreapNode *x = y->l;
        treap_push(x);
        y->l = x->r;
        x->r = y;
        treap_pull(y);
        treap_pull(x);
        return x;
    }
    
    TreapNode* rotate_left(TreapNode *x) {
        treap_push(x);
        TreapNode *y = x->r;
        treap_push(y);
        x->r = y->l;
        y->l = x;
        treap_pull(x);
        treap_pull(y);
        return y;
    }
    
    TreapNode* treap_insert(TreapNode *root, TreapNode *node) {
        if (!root) return node;
        treap_push(root);
        if (treap_less(node, root)) {
            root->l = treap_insert(root->l, node);
            if (root->l->pri > root->pri) root = rotate_right(root);
        } else {
            root->r = treap_insert(root->r, node);
            if (root->r->pri > root->pri) root = rotate_left(root);
        }
        treap_pull(root);
        return root;
    }
    
    int64 query_prefix_minus(TreapNode *root, int64 A) {
        if (!root) return INF64;
        treap_push(root);
        if (root->a > A) {
            return query_prefix_minus(root->l, A);
        }
        int64 res = root->d - root->a;
        if (root->l) res = min(res, root->l->mn_minus);
        res = min(res, query_prefix_minus(root->r, A));
        return res;
    }
    
    int64 query_suffix_plus(TreapNode *root, int64 A) {
        if (!root) return INF64;
        treap_push(root);
        if (root->a < A) {
            return query_suffix_plus(root->r, A);
        }
        int64 res = root->d + root->a;
        if (root->r) res = min(res, root->r->mn_plus);
        res = min(res, query_suffix_plus(root->l, A));
        return res;
    }
    
    int64 treap_query(TreapNode *root, int64 A, int64 D) {
        if (!root) return INF64;
        int64 ans = INF64;
        int64 x = query_prefix_minus(root, A);
        if (x < INF64 / 2) ans = min(ans, D + A + x);
        x = query_suffix_plus(root, A);
        if (x < INF64 / 2) ans = min(ans, D - A + x);
        return ans;
    }
    
    void treap_flatten(TreapNode *root, vector<TreapNode*> &nodes) {
        if (!root) return;
        treap_push(root);
        TreapNode *left = root->l;
        TreapNode *right = root->r;
        treap_flatten(left, nodes);
        treap_flatten(right, nodes);
        root->l = root->r = nullptr;
        root->lazy = 0;
        treap_pull(root);
        nodes.push_back(root);
    }
    
    void merge_group(TreapNode *&acc, TreapNode *group, int64 &best) {
        if (!group) return;
        if (!acc) {
            acc = group;
            return;
        }
        if (treap_size(acc) < treap_size(group)) swap(acc, group);
    
        vector<TreapNode*> nodes;
        nodes.reserve(treap_size(group));
        treap_flatten(group, nodes);
    
        for (TreapNode *p : nodes) {
            best = min(best, treap_query(acc, p->a, p->d));
        }
        for (TreapNode *p : nodes) {
            acc = treap_insert(acc, p);
        }
    }
    
    struct Event {
        int64 g;
        int color;
        int node;
        bool operator<(const Event &other) const {
            return g < other.g;
        }
    };
    
    struct Query {
        int node;
        int64 K;
        int id;
        bool operator<(const Query &other) const {
            return K < other.K;
        }
    };
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int n, m, q;
        cin >> n >> m >> q;
    
        vector<int64> color_weight(m + 1);
        for (int c = 1; c <= m; ++c) cin >> color_weight[c];
    
        vector<int> color(n + 1);
        for (int i = 1; i <= n; ++i) cin >> color[i];
    
        vector<int64> a(n + 1);
        for (int i = 1; i <= n; ++i) cin >> a[i];
    
        vector<vector<Edge>> graph(n + 1);
        for (int i = 1; i < n; ++i) {
            int u, v;
            int64 w;
            cin >> u >> v >> w;
            graph[u].push_back({v, w});
            graph[v].push_back({u, w});
        }
    
        vector<int> parent(n + 1, 0), depth(n + 1, 0), tin(n + 1), tout(n + 1);
        vector<int64> dist_root(n + 1, 0);
        vector<int> preorder;
        preorder.reserve(n);
        vector<int> iter(n + 1, 0), stack_nodes;
        stack_nodes.reserve(n);
        int timer = 0;
        stack_nodes.push_back(1);
        parent[1] = 0;
    
        while (!stack_nodes.empty()) {
            int u = stack_nodes.back();
            if (iter[u] == 0) {
                tin[u] = ++timer;
                preorder.push_back(u);
            }
            if (iter[u] == (int)graph[u].size()) {
                tout[u] = timer;
                stack_nodes.pop_back();
                continue;
            }
            Edge e = graph[u][iter[u]++];
            if (e.to == parent[u]) continue;
            parent[e.to] = u;
            depth[e.to] = depth[u] + 1;
            dist_root[e.to] = dist_root[u] + e.w;
            stack_nodes.push_back(e.to);
        }
    
        int LOG = 1;
        while ((1 << LOG) <= n) ++LOG;
        vector<vector<int>> up(LOG, vector<int>(n + 1, 0));
        for (int u = 1; u <= n; ++u) up[0][u] = parent[u];
        for (int k = 1; k < LOG; ++k) {
            for (int u = 1; u <= n; ++u) {
                up[k][u] = up[k - 1][up[k - 1][u]];
            }
        }
    
        auto is_ancestor = [&](int u, int v) -> bool {
            return tin[u] <= tin[v] && tout[v] <= tout[u];
        };
    
        auto lca = [&](int u, int v) -> int {
            if (is_ancestor(u, v)) return u;
            if (is_ancestor(v, u)) return v;
            int x = u;
            for (int k = LOG - 1; k >= 0; --k) {
                if (up[k][x] && !is_ancestor(up[k][x], v)) x = up[k][x];
            }
            return parent[x];
        };
    
        auto kth_ancestor = [&](int u, int k) -> int {
            for (int b = 0; b < LOG; ++b) {
                if (k & (1 << b)) u = up[b][u];
            }
            return u;
        };
    
        vector<int> subtree_size(n + 1, 1), heavy(n + 1, 0);
        for (int idx = n - 1; idx >= 0; --idx) {
            int u = preorder[idx];
            int best_size = 0;
            for (const Edge &e : graph[u]) {
                int v = e.to;
                if (parent[v] != u) continue;
                subtree_size[u] += subtree_size[v];
                if (subtree_size[v] > best_size) {
                    best_size = subtree_size[v];
                    heavy[u] = v;
                }
            }
        }
    
        vector<int> head(n + 1), pos(n + 1), rev_pos(n + 1);
        int pos_timer = 0;
        vector<pair<int,int>> chain_tasks;
        chain_tasks.push_back({1, 1});
        while (!chain_tasks.empty()) {
            auto [start, top] = chain_tasks.back();
            chain_tasks.pop_back();
            vector<pair<int,int>> light_tasks;
            for (int u = start; u != 0; u = heavy[u]) {
                head[u] = top;
                pos[u] = ++pos_timer;
                rev_pos[pos_timer] = u;
                for (const Edge &e : graph[u]) {
                    int v = e.to;
                    if (parent[v] == u && v != heavy[u]) light_tasks.push_back({v, v});
                }
            }
            for (auto &task : light_tasks) chain_tasks.push_back(task);
        }
    
        Fenwick bit(n);
        auto path_add = [&](int u, int v, int64 delta) {
            while (head[u] != head[v]) {
                if (depth[head[u]] > depth[head[v]]) swap(u, v);
                bit.range_add(pos[head[v]], pos[v], delta);
                v = parent[head[v]];
            }
            if (depth[u] > depth[v]) swap(u, v);
            bit.range_add(pos[u], pos[v], delta);
        };
    
        vector<vector<int>> occurrences(m + 1);
        for (int u : preorder) occurrences[color[u]].push_back(u);
    
        vector<Event> events;
        events.reserve(2 * n);
        TreapPool treap_pool(n);
    
        for (int c = 1; c <= m; ++c) {
            const vector<int> &nodes = occurrences[c];
            if (nodes.size() < 2) continue;
    
            vector<int> all = nodes;
            all.reserve(nodes.size() * 2);
            for (int i = 1; i < (int)nodes.size(); ++i) {
                all.push_back(lca(nodes[i - 1], nodes[i]));
            }
            sort(all.begin(), all.end(), [&](int x, int y) { return tin[x] < tin[y]; });
            all.erase(unique(all.begin(), all.end()), all.end());
    
            int k = (int)all.size();
            vector<int> virtual_parent(k, -1), st;
            st.reserve(k);
            st.push_back(0);
            for (int i = 1; i < k; ++i) {
                while (!is_ancestor(all[st.back()], all[i])) st.pop_back();
                virtual_parent[i] = st.back();
                st.push_back(i);
            }
    
            vector<TreapNode*> accumulator(k, nullptr);
            vector<int64> best(k, INF64);
    
            for (int i = k - 1; i >= 0; --i) {
                int u = all[i];
                if (color[u] == c) {
                    TreapNode *single = treap_pool.make_node(u, a[u], 0);
                    merge_group(accumulator[i], single, best[i]);
                }
    
                if (best[i] < INF64 / 2) {
                    events.push_back({best[i], c, u});
                }
    
                int p = virtual_parent[i];
                if (p != -1) {
                    int64 delta = dist_root[u] - dist_root[all[p]];
                    treap_apply(accumulator[i], delta);
                    merge_group(accumulator[p], accumulator[i], best[p]);
                }
            }
        }
    
        vector<Query> queries(q);
        for (int i = 0; i < q; ++i) {
            cin >> queries[i].node >> queries[i].K;
            queries[i].id = i;
        }
    
        sort(events.begin(), events.end());
        vector<Query> sorted_queries = queries;
        sort(sorted_queries.begin(), sorted_queries.end());
    
        vector<set<int>> active(m + 1);
        vector<int64> answers(q);
        size_t event_ptr = 0;
    
        auto activate_event = [&](const Event &ev) {
            int c = ev.color;
            int z = ev.node;
            auto &S = active[c];
            if (S.empty()) {
                path_add(1, z, color_weight[c]);
                S.insert(tin[z]);
                return;
            }
    
            auto it = S.lower_bound(tin[z]);
            int h = 0;
            if (it != S.end()) {
                int y = preorder[*it - 1];
                h = lca(z, y);
            }
            if (it != S.begin()) {
                int y = preorder[*prev(it) - 1];
                int h2 = lca(z, y);
                if (h == 0 || depth[h2] > depth[h]) h = h2;
            }
    
            if (h != z) {
                int steps = depth[z] - depth[h] - 1;
                int first_new = kth_ancestor(z, steps);
                path_add(first_new, z, color_weight[c]);
            }
            S.insert(tin[z]);
        };
    
        for (const Query &qu : sorted_queries) {
            while (event_ptr < events.size() && events[event_ptr].g <= qu.K) {
                activate_event(events[event_ptr]);
                ++event_ptr;
            }
            answers[qu.id] = bit.point_query(pos[qu.node]);
        }
    
        for (int i = 0; i < q; ++i) cout << answers[i] << '\n';
        return 0;
    }
    
    • 1

    Information

    ID
    229
    Time
    6000ms
    Memory
    256MiB
    Difficulty
    9
    Tags
    # Submissions
    66
    Accepted
    3
    Uploaded By