YS - Vertex Set Path Composite

Author: Andrew Cheng


Time Complexity: O(Nlog2N)\mathcal{O}(N \log^2 N) from HLD

Main Idea: Different from a classic HLD problem, the nesting of functions does not follow the commutative property. In other words, the answer of the query 11 uu vv xx is different from the answer of the query 11 vv uu xx.

To solve this problem, we can break down the path from node uu to node vv into two paths: from node uu to LCA(u,v)LCA(u,v) and from LCA(u,v)LCA(u,v) to node vv. The path from node uu to LCA(u,v)LCA(u,v) will decrease in depth, and the path from LCA(u,v)LCA(u,v) to node vv will increase in depth.

We can then maintain two segment trees.

The first segment tree will calculate the equivalent function that results from moving from node uu to LCA(u,v)LCA(u,v). And the second segment tree will calculate the equivalent function that results from moving from LCA(u,v)LCA(u,v) to node vv. After this we can plug in the given xx into the two functions to get the answer of the query.

It should be mentioned that the function at node LCA(u,v)LCA(u,v) should only be calculated once. To avoid calculating the node twice, we can intentionally avoid LCA(u,v)LCA(u,v) during exactly one of the two path queries.

The update queries can be implemented using segment tree point updates on both segment trees.

C++

#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
const int maxN = 2e5 + 5;
const int height = 25;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!