We need to process two types of queries on a tree with n up to 1e5, m up to 1e5. Initially only node 1 is red; others blue. There are two operations: type 1: paint a blue node red (note: no repainting of red nodes? It says paint a specified blue node in red. So we can assume the node is currently blue, and we make it red). Type 2: given node v, find the minimum distance from v to any red node, and output that distance.
We need to answer queries online.
A classic problem: dynamic nearest red node queries. Usually solved with centroid decomposition or sqrt decomposition or maintaining a set of red nodes and using multi-source BFS updates. Since we have up to 1e5 nodes and queries, we need something efficient.
Observations: Initially only one red node. Red nodes are only added, never removed. So the set of red nodes grows over time. We need to answer distance to nearest red node for any node at any time.
One approach: Use a data structure that supports adding a red node and querying min distance. For each node, we need to maintain the current distance to the nearest red node. Adding a red node may affect distances for many nodes (the whole tree). But we can use a BFS from the newly added red node, updating distances only if they improve. However, doing BFS each time could be O(n) per addition, leading to O(n*m) in worst-case, which is too slow.
We can use "centroid decomposition" to answer queries in O(log^2 n) per query and addition? Actually, typical solution: maintain for each node the distance to the nearest red node, and use a BFS-like approach but with a trick: only perform BFS when enough red nodes have been added (sqrt decomposition). Another common solution: use "small to large" in centroid tree: for each centroid, maintain the minimum distance from red nodes in its subtree. Then for query at node v, we consider all centroids on the path from v to root in the centroid tree, and compute the distance via those centroids. For each addition, we update the centroids along the path. This yields O(log n) per operation (since centroid tree height O(log n)). Actually, typical "Dynamic Tree Queries - Nearest Marked Node" can be solved with centroid decomposition.
Let's recall: Build centroid decomposition of the tree. For each centroid C, we store two pieces of information: For each node in the subtree of that centroid (the original tree) that belongs to the component handled by C, we can compute distances between nodes and C. Then for query node v, we can consider all ancestors (in centroid tree) of v, and compute d(v, centroid) + minDist[centroid] where minDist[centroid] is the minimum distance from any red node in that centroid's component to the centroid. But careful: Actually the typical technique: For each node, we maintain an array best per centroid on the path from node to root in centroid tree, storing distance from node to centroid? No, we compute distances on the fly using LCA for distance queries. But we can preprocess LCA to compute distance between any two nodes in O(1) or O(log n) (using binary lifting). However, we also need to update when a node becomes red.
Simplify: Use centroid decomposition to maintain, for each centroid, the minimal distance from any red node in its component (the entire tree originally, but each centroid covers nodes that are in its subtree in the centroid tree). Actually, centroid decomposition partitions the tree recursively. The centroid tree is built where each centroid is parent of centroids of the subtrees after removing the centroid. For each centroid node C in centroid tree, we can maintain a value best[C], which is the minimum distance from any red node in the "subtree" of the centroid tree rooted at C? That might not be straightforward: because the component of C consists of all nodes that are in the original tree that are in the same region as C when we remove its ancestors in centroid tree. Typically, we maintain for each node v, for each ancestor centroid anc of v in the centroid tree, the distance between v and anc. Then for each centroid, we keep a multiset of distances from red nodes that are in its "region" to that centroid. Then for query v, we consider each ancestor centroid anc of v: the distance from v to anc + (the minimum distance among red nodes in anc's region to anc). This yields the candidate distance via that centroid. Because any red node in anc's region can be reached via anc? Actually, careful: In centroid decomposition approach for nearest marked node, we store for each centroid the minimum distance to a red node in its component (i.e., the part of the tree that is under the centroid in the decomposition). Then for a query node v, we look at all centroids on the path from v to root in centroid tree. For each such centroid c, we compute dist(v, c) + best[c]. However, this might overcount? But it's correct because any red node is in the component of some centroid that is an ancestor of v? Actually, any red node lies in the subtree of some centroid relative to the centroid tree? Actually, property: For any two nodes u and v, there exists a unique centroid on the path between them that is the LCA in the centroid tree? Not exactly. But known technique: For each node, we store distances to all centroids on the path from that node to the root of the centroid tree. Then for a red node u, we update all centroids on the path from u to the root: for each centroid c, we consider distance from u to c, and update best[c] = min(best[c], dist(u,c)). For a query node v, we compute min over all centroids c on the path from v to root of dist(v,c) + best[c]. This yields the distance from v to the closest red node. Why? Because for any red node u, let c be the first (lowest) centroid that is common to both u and v in the centroid tree? Actually, there is a centroid that is the LCA of u and v in the centroid tree. That centroid lies on the paths from u to root and from v to root. For that centroid c, we have dist(u,v) = dist(u,c) + dist(v,c). Because c lies on the path between u and v? In centroid decomposition, it's a known property: The LCA in the centroid tree of two nodes lies on the path between them in the original tree, and the distance between the two nodes is dist(u, c) + dist(v, c). Actually, is that true? Let's recall: In centroid decomposition, each centroid separates its component into subtrees. The centroid tree is built such that each node's parent is the centroid that separated it from the rest. For any two nodes u and v, the centroid that is their LCA in the centroid tree is the first centroid that, when removed, separates u and v into different components. That centroid lies on the path between u and v. So indeed, for that centroid c, the shortest path from u to v goes through c? Actually, if c lies on the path between u and v, then distance is dist(u,c) + dist(v,c). But is c always on the path? In centroid decomposition, the centroid that is LCA of u and v is a node that is on the path between u and v. Yes, that's a property: The LCA in centroid tree is the centroid that first separated u and v. It is the first centroid that, when removed, u and v are in different components, implying that the centroid lies on the path between u and v. So indeed, dist(u,v) = dist(u, c) + dist(v, c). Therefore, if we have for each centroid c the minimum dist(u,c) over all red nodes u that are in the subtree of c (i.e., those for which c is an ancestor in centroid tree), then for a query v, we can compute min_c (dist(v,c) + best[c]) because for any red node u, let c be the LCA in centroid tree of u and v; then u contributes dist(v,c) + dist(u,c) as a candidate. And since we store best[c] = min_{red u in subtree of c} dist(u,c), then dist(v,c) + best[c] is at most dist(v,u) for some u with that LCA. And we take min over all c, we get the answer. But we need to ensure that for any red node u, there exists a centroid c on the path from v to root (and also from u to root) such that c = LCA(u,v) and we consider that c. Since c is an ancestor of v in centroid tree (because c is LCA, so it's on path from v to root), it's included. So indeed, the method works if we update best[c] for all centroids on the path from a red node to the root, using dist(u,c). And for query, we consider all centroids on path from v to root, compute dist(v,c) + best[c] and take min.
Thus we can support operations:
- Build centroid decomposition O(n log n) (with distances from each node to each centroid ancestor). For each node, store list of pairs (centroid, distance) for all its ancestors in the centroid tree.
- Maintain best array for each centroid, initially INF, except for node 1 initially red: we update all its ancestors with dist(1, centroid) = compute distances. Then for each type 1 (paint blue node v red), we update all centroids c in ancestors of v: best[c] = min(best[c], dist(v,c)).
- For type 2 (query for node v), compute ans = INF, for each centroid c in ancestors of v: ans = min(ans, dist(v,c) + best[c]). Output ans.
Complexities: Each node appears in O(log n) centroids (since centroid tree height is O(log n)). So per update and query, we iterate over O(log n) centroids. The distance between v and centroid c can be retrieved from the precomputed list? For each node v, we can store for each ancestor centroid c, the distance d(v,c). That can be computed during centroid decomposition DFS. So queries are O(log n). Updates are O(log n). Building is O(n log n). This fits constraints.
We must also compute LCA distances quickly? Actually we can compute distances on the fly via precomputed depths and LCA, but storing per node per ancestor distance is easier and still O(n log n) memory (n * log n up to 1e5 * 17 = 1.7e6, which is fine). So we can compute distances during centroid decomposition: For each centroid, we run a DFS to compute distances from that centroid to all nodes in its current component, and for each node visited, we add an entry (centroid, distance) to its list. Then we recursively decompose the subtrees (components after removing centroid). This yields for each node, a list of all centroids that are ancestors in centroid tree, with distance. So we can store that in an array info[v] as a vector of pairs (centroid, dist). Later we use this for queries and updates.
Implementation details:
- Input tree: adjacency list.
- Preprocess LCA? Not necessary if we compute distances directly in centroid DFS. Because when we are in a component, we can compute distances from centroid using simple DFS/BFS that stays within the component. But careful: For each centroid decomposition step, we need to know which nodes belong to the component. We can use a visited array for centroids? Alternatively, we can do typical centroid decomposition: we compute subtree sizes, find centroid, then we process that centroid: for each neighbor (adjacent node) that hasn't been removed (i.e., not assigned to a parent centroid), we perform a DFS that computes distances from centroid to nodes in that subtree, and we record for each node in that subtree the distance (distance from centroid) and add centroid to node's list. Actually, for each node, we need distances to all ancestor centroids. So when we process centroid c, we should record for all nodes in the entire component (including c itself) the distance from c. But careful: The centroid decomposition partitions the tree; after removing c, the remaining components are each processed separately, and later in those components, nodes will get distances to their higher-level centroids (ancestors in centroid tree). So when we are at centroid c, we need to traverse all nodes in the current component (i.e., the part of the tree that is currently being decomposed) and record for each node the distance to c. Since we are about to remove c and then recurse into each subtree, the nodes in each subtree will later get distances to higher-level centroids (which are ancestors of c? Actually c is the current root of this decomposition step; ancestors of c in the centroid tree are already recorded earlier? The order is top-down: we start with the whole tree, find its centroid, that centroid becomes the root of centroid tree. For each node in the tree, we record distance to that centroid. Then we remove that centroid, and recursively find centroids for each component; those centroids become children of the root. For each node in those subtrees, when we process the child centroid, we will also record distance to that child centroid (which is an ancestor of the node in the centroid tree? Actually, the node is in the subtree of the child centroid; so the child centroid is its "parent" in centroid tree? The centroid tree is built such that each node's parent is the centroid that was responsible for the component that contained the node at the previous level. For any node, the centroids on the path from it to the root of centroid tree are exactly the centroids encountered during decomposition: the centroid of the whole tree (root), then the centroid of the component containing the node after removing root, etc. So we need to record distances to all those centroids. So in the recursive step, for a given component, we find its centroid, and then for all nodes in that component, we record the distance to that centroid. But we must be careful: The component may not include all nodes originally; it's the part that remains after removing higher-level centroids. That's fine. So typical algorithm: For each node, maintain a vector or . We'll have a global vector of size n+1 maybe as vector of pairs. In the centroid decomposition function or we just recursively process and pass the set of nodes? But to compute distances, we need to traverse the component from the centroid. We can do: In function that finds centroid for the tree rooted at u? But we need to handle removal. Standard centroid decomposition uses a array marking removed centroids. Steps:
- Compute subtree sizes via DFS, ignoring dead nodes.
- Find centroid of current component.
- Mark centroid as dead (so it's removed).
- For the centroid, we want to store for all nodes in the component (excluding dead nodes) the distance to centroid. But careful: The component includes all nodes reachable without passing through dead nodes, which is exactly the component. So we can do a DFS from centroid, traversing only non-dead nodes, and record distance from centroid. For each node v visited, we push (centroid, distance) into an array for v.
- Then for each neighbor of centroid that is not dead, recursively decompose that neighbor's subtree (i.e., call build on that neighbor) with the centroid as parent? But we don't need parent for the algorithm; we only need to compute distances. The recursion will take care of recording distances to deeper centroids.
Thus each node will accumulate O(log n) entries.
After building, we have:
distInfo[v] : vector of (centroid, dist) for each centroid that is an ancestor of v in the centroid tree, including the centroid that is v itself if v becomes a centroid at some level? Yes.
Now we need to answer queries:
- Type 1: node v becomes red. For each (c, d) in distInfo[v], we update
best[c] = min(best[c], d).
- Type 2: node v query. Initialize ans = INF. For each (c, d) in distInfo[v], ans = min(ans, d + best[c]). Print ans.
We also need to handle initial state: node 1 is initially red. So we do the update for node 1 as if it was painted red at start.
Edge Cases: Node 1 may be painted again later? It is already red, but queries only paint blue nodes. So we don't need to worry about repainting red.
Implementation details:
-
n up to 1e5, adjacency list.
-
For centroid decomposition, we need to compute sizes and centroids efficiently. We'll have arrays: dead[n+1] bool, subsize[n+1].
-
In the DFS to compute subtree sizes, we pass a starting node and avoid dead nodes. But we also need to know total size of current component to find centroid. So typical pattern:
void dfsSize(int u, int p) {
subsize[u] = 1;
for (int v : adj[u]) if (v != p && !dead[v]) {
dfsSize(v, u);
subsize[u] += subsize[v];
}
}
Then find centroid: start from the root of component (any node, say the one passed), and while there exists a child with subsize > total/2, move to that child. Implementation:
int findCentroid(int u, int p, int total) {
for (int v : adj[u]) if (v != p && !dead[v]) {
if (subsize[v] > total/2) return findCentroid(v, u, total);
}
return u;
}
But careful: The centroid condition is that for all subtrees after removing node, each subtree size <= total/2. The above approach works if we have correct subsize from the root. However, the subsize values computed from the root may not reflect the correct sizes for all neighbors because we computed sizes with root at some node. But the algorithm typical: after computing sizes, we start from the same root and check condition: for each neighbor, if subsize[neighbor] > total/2, move to that neighbor. But also need to consider the component "upward" (the rest of tree) which has size total - subsize[u]; that should also be <= total/2. When moving to neighbor, we need to adjust subsize? Actually the typical centroid finding uses a second DFS that checks both sides: subsize[child] and total - subsize[u]. The simple loop may not be sufficient because the parent side is not accounted. However, the algorithm that moves only if a child > total/2 and also checks the parent side after moving? Usually the code is:
int getCentroid(int u, int p, int total) {
for (int v : adj[u]) if (v != p && !dead[v]) {
if (subsize[v] > total/2) return getCentroid(v, u, total);
}
return u;
}
But this may return a node that does not satisfy the condition because the "rest" may be > total/2. However, if we start from the root of the DFS (the one we used to compute subsize), the rest is total - subsize[u]. If we find a node where no child has size > total/2, it could be that total - subsize[u] > total/2. But if that happens, then the parent side is too large, meaning the centroid lies in the direction of the parent. But if we started from the root and we only move to children, we might not reach the centroid if it's in the parent direction. However, we can ensure that the root we start with is somewhere in the component; the centroid may be in a different branch. The typical centroid finder after size computation does: start at the root, and while there exists a neighbor (including possibly parent) with subsize > total/2, move to that neighbor. But since we don't have a parent pointer, we need to handle the "rest". A common approach: After computing subsize from an arbitrary root (say the node passed as u), we call a function that for each neighbor v (except p and dead), if subsize[v] > total/2, we go there; also we need to check if total - subsize[u] > total/2, then the centroid is in the parent side. But we don't have a parent side's specific node. However, we can treat the parent side as a "virtual" subtree; but we can simply start from the root of the component (the node we called size DFS on) and then after the loop, we need to check if total - subsize[current] > total/2. If so, then we need to move to the parent? But we don't have a parent reference. But we can recall that the root we started from had subsize[root] = total. So if we end up at a node where total - subsize[node] > total/2, then the centroid must be on the path from the root to node, specifically in the direction of the root. To find it, we could have tracked parent during the search. Another approach: Do a second DFS that specifically checks both children and the rest. A robust method: In the function, we pass the node and its parent. At each step, after checking children, we also check if total - subsize[u] > total/2, then we need to go to the parent. But we cannot go to parent without knowing which node is the parent in the DFS? Actually we do have parent p. So we can check: if total - subsize[u] > total/2, then the centroid is somewhere in the parent side, so we recursively call find_centroid(p, u, total) but note that p might be dead? Not dead because parent is part of same component. However, we need to ensure we can compute subsize for the parent correctly? The subsize values are from the original DFS which had root at the starting node; they are relative to that root. The parent's subsize includes the current node's subtree as part of it; but if we go up to parent, we need to adjust? Actually, we can compute the centroid using a DFS that checks both conditions and moves appropriately:
Thus centroid decomposition can be implemented as:
- Global arrays:
dead, subsize.
- For each node, a list
cenDist as vector<pair<int,int>> or two vectors.
We also need to compute distances from centroid to all nodes in its component. We'll have a DFS function addDistance(centroid, node, parent, dist) that pushes (centroid, dist) into the node's list and recurses to neighbors not dead. We can call it for each neighbor of centroid: for each neighbor v not dead, call dfsDist(centroid, v, centroid, 1) (distance 1). Also centroid itself: (centroid, 0) added. Or we can incorporate in the same DFS: start at centroid with distance 0, for each neighbor if not dead, do DFS.
Then mark centroid as dead, and recursively decompose each neighbor's subtree: for each neighbor v of centroid not dead, we compute sizes for that component by doing dfsSize(v, -1) within that component, then find its centroid, and call decompose on that centroid.
Implementation:
void dfsSize(int u, int p) {
subsize[u] = 1;
for (int v : adj[u]) {
if (v != p && !dead[v]) {
dfsSize(v, u);
subsize[u] += subsize[v];
}
}
}
void dfsDist(int u, int p, int centroid, int d) {
distInfo[u].emplace_back(centroid, d);
for (int v : adj[u]) {
if (v != p && !dead[v]) {
dfsDist(v, u, centroid, d+1);
}
}
}
int findCentroid(int u, int p, int total) {
for (int v : adj[u]) {
if (v != p && !dead[v]) {
if (subsize[v] > total/2) {
return findCentroid(v, u, total);
}
}
}
return u;
}
void decompose(int u) {
dfsSize(u, -1);
int c = findCentroid(u, -1, subsize[u]);
// Now process centroid c
// Record distance from c to all nodes in its component
dfsDist(c, -1, c, 0);
dead[c] = true;
// Recurse on each component
for (int v : adj[c]) {
if (!dead[v]) {
decompose(v);
}
}
}
But careful: In decompose, after we compute sizes for the whole component with root u, we find centroid c. Then we call dfsDist from c to all nodes in that component. However, dfsDist traverses all nodes reachable without passing through dead nodes. Since we haven't marked any node dead yet except previously processed centroids, and we just computed the component from u, which includes all nodes not dead. That's fine. However, note that dfsDist will also go into subtrees that will later be decomposed, but that's fine; we record the distance to this centroid for all nodes in the component. That includes nodes that are in other components after removing c? Actually, after we mark c dead, the rest of the nodes are partitioned into components each connected through a neighbor of c. dfsDist will record distances from c to all those nodes. That's correct: all nodes that are in the component (including all nodes that are currently not dead) will have this centroid as one of their ancestors in centroid tree, because c is the centroid for this component. In the centroid tree, c becomes parent of the centroids of the subcomponents. So all nodes in those subcomponents should have c in their list. So dfsDist should be called before marking c dead? Actually it's fine to call it before marking dead, but we must ensure that dfsDist doesn't cross dead nodes; there are none other than previous centroids which are already dead; but those are not in the current component because we have restricted to nodes not dead. So we can call it before marking c dead, but then we must ensure dfsDist does not traverse into dead nodes (which are not present). So that's fine.
But after we mark c dead, we need to recursively decompose each neighbor's component. However, we should compute sizes for each subcomponent separately. In the code above, after marking c dead, we call decompose(v) for each neighbor v not dead. But note: decompose(v) will call dfsSize(v, -1) which will compute sizes for the subcomponent containing v, but since c is dead, the DFS will not cross into other subcomponents, so it's correct. But we need to ensure we pass the root of that subcomponent, which is v. However, decompose(v) will treat v as the starting point for size DFS; this will correctly compute the component's total size and find its centroid. So it's fine.
Potential issue: In decompose(u), we first call dfsSize(u,-1). But u might be a node that is not the centroid of the whole component? Actually, we call decompose with the root of the whole tree initially (node 1). Then after we find centroid, we decompose each neighbor. So the decompose calls for subcomponents will be with starting node equal to that neighbor. That's fine.
Thus building centroid decomposition and distance info is straightforward.
Complexities: O(n log n) time and memory.
After building, we have distInfo[v] with pairs (centroid, distance). We'll also need an array best for each centroid, initialized to INF. For node 1 initial red, we update best for all centroids in its list: for each (c,d) in distInfo[1], best[c] = min(best[c], d). That's O(log n).
Now process queries:
- For type 1: v becomes red. For each (c,d) in distInfo[v], best[c] = min(best[c], d). (Note: v may have been red already? Input guarantees it's blue, so no duplicate.)
- For type 2: compute ans = INF; for each (c,d) in distInfo[v], ans = min(ans, d + best[c]); output ans.
Potential problem: Could ans be INF? Initially best[some centroids] might be INF for centroids that are not ancestors of node 1? But node 1 is ancestor of all centroids? Actually, node 1 is in the whole tree, and it will be in all components? Not necessarily. In centroid decomposition, each node appears in multiple centroids' lists: all centroids that are ancestors in the centroid tree. For node 1, it will be in the lists of centroids that are on the path from root centroid to the centroid where node 1's own leaf? Actually node 1 is a regular node, not necessarily a centroid. The centroid tree's root is the centroid of the whole tree. Node 1 is somewhere in the tree, so its list includes the root centroid, and then the centroid of the component it falls into after removing root, and so on. So all centroids that are ancestors of node 1 (in centroid tree) will have node 1 in their component. So after updating node 1, best for those centroids gets finite values. For other centroids that are not ancestors of node 1, best remains INF. For query v, we only consider centroids that are ancestors of v. But some of those centroids may not have any red node in their component yet (i.e., best is INF). But the correct answer will be from a centroid that is an ancestor of both v and some red node. If there is no red node in a given centroid's component, then that centroid's best is INF, and it doesn't affect min. However, if there is a red node elsewhere, there will be some common ancestor centroid that includes both. So it's fine.
One more nuance: The centroid tree height is O(log n). But we need to ensure that the list for each node indeed contains O(log n) entries. The decomposition recursion depth is O(log n) and each node appears in exactly one centroid per level, so yes.
Now we need to implement LCA? Not needed because distances are computed during centroid DFS. However, the distances we computed during centroid DFS are exact distances in the original tree. Since we are doing a DFS from centroid within the component, we compute distances by incrementing by 1 per edge. That yields correct distance because the component is a connected subgraph of the original tree, and edges are original. So it's fine.
Implementation steps:
- Read n, m.
- Build adjacency list (size n+1).
- Preprocess centroid decomposition:
- Allocate
dead bool array (size n+1, initially false).
subsize int array.
distInfo vector of vector<pair<int,int>> for each node (or two separate vectors for centroids and distances). We'll use vector<pair<int,int>>.
- Call
decompose(1).
- Initialize
best array (size n+1) to some large value (e.g., INF = 1e9).
- Process initial red node 1: for each (c,d) in distInfo[1], best[c] = min(best[c], d).
- Process queries:
For each query (t, v):
- if t==1: for each (c,d) in distInfo[v], if (d < best[c]) best[c] = d.
- else: ans = INF; for each (c,d) in distInfo[v], ans = min(ans, d + best[c]); print ans.
But note: In type 1, we are setting best[c] to min of existing and d. But we may need to update best for all centroids on path from v to root. That's what we do.
Check correctness: For query, ans = min_{c in ancestors(v)} (dist(v,c) + best[c]) where best[c] = min_{red u in subtree of c} dist(u,c). Since for any red u, the LCA in centroid tree c' is an ancestor of v, and best[c'] <= dist(u,c'), so dist(v,c')+best[c'] <= dist(v,c')+dist(u,c') = dist(v,u). So ans <= true min. Also, ans comes from some red u' (the one achieving best for some c), and that gives distance exactly dist(v, u'). So ans equals min distance.
Edge Cases: Node v itself may be red. For type 2 query on a red node, distance should be 0. Does our method yield 0? If v is red, then for the centroid c = v? But v is a node, not necessarily a centroid. However, we updated best for centroids on v's path. For the centroid that is the one where v is the centroid itself? Actually v might be a centroid at some level if v becomes a centroid during decomposition. But not guaranteed. However, if v is red, then when we process type 2 for v, we consider all centroids c on its ancestor list. For some centroid c, best[c] might be 0 if that centroid itself is red? Wait, v is red but not necessarily a centroid. However, there is a centroid c on v's ancestor list such that v is in its component and best[c] is the min distance from red nodes in that component to c. Since v is red, best[c] could be dist(v,c). So for that centroid c, dist(v,c) + best[c] = 2*dist(v,c), which is > 0 unless dist(v,c)=0 (i.e., v == c). But if v is not a centroid, then no centroid exactly equals v. So we would not get 0. That's a problem! Because the distance from v to the nearest red node (including itself) should be 0 if v itself is red. How to handle that?
Our method only considers distances via centroids. But if v is itself a red node, the closest red node is v, distance 0. However, our candidate expression dist(v,c) + best[c] might not capture 0 because best[c] = min_{red u} dist(u,c). If v is red, then best[c] <= dist(v,c). So dist(v,c) + best[c] could be as low as 2dist(v,c) if best[c] = dist(v,c) from some other red? Actually if v is the only red in that component, then best[c] = dist(v,c). So dist(v,c) + best[c] = 2dist(v,c) which is > 0. So our method fails to give 0. We need to handle the case where the query node is red separately. But also the method should be able to give 0 if we consider the centroid that is exactly the node v? But v may not be a centroid. However, there is also possibility to consider the red node itself directly. In typical implementations of this centroid decomposition for "nearest marked node", they also store for each node its own "marked" status and check if it's marked before iterating over centroids. Because the centroid-based expression gives distance to some other marked node, not necessarily itself. So we need to check if the node itself is marked (red). So we should maintain a boolean array isRed. Initially, isRed[1]=true; else false. For type 1, set isRed[v]=true. For type 2 query, if isRed[v] then answer 0. Else compute via centroids.
But wait, is that sufficient? Consider node v that is not red but there is a red node at distance 0? No, only red nodes themselves give distance 0. So yes.
Now, what about the case where v is red and also there is another red node even closer? Actually distance 0 is min. So we can just output 0.
Thus we need to maintain isRed.
Now what about the update of best when marking a node red? Should we also consider that node's distance to itself is 0, but that would correspond to a centroid that is exactly that node? If the node itself is a centroid, then best[node] could be updated to 0. However, if the node is not a centroid, its own list doesn't include itself as a centroid; so we cannot set best[non-centroid] because best is only defined for centroids. But we might need to consider that node itself is red for queries on other nodes? But the method works because for any other node w, the LCA centroid of w and red node v will be some centroid on both their paths, and best for that centroid will be updated with dist(v, that centroid). So the distance from w to v will be captured. For queries on v itself, we handle separately. So all good.
But wait: For query on a node w that is red? Already handled. For query on w that is not red, we will consider all centroids. If there is a red node v such that the LCA centroid c has best[c] = dist(v,c). Then w's distance candidate = dist(w,c)+dist(v,c) = dist(w,v). So works.
Implementation details:
distInfo should be a vector of vectors. For n=1e5, total entries ~ n log n ~ 1.7e6, each pair two ints, memory okay.
best array: size n+1, initialize INF.
isRed array bool.
Now ensure that initial node 1 is red: isRed[1]=true; update best for its centroids.
Now processing queries.
But there is a nuance: When we add a red node v, we update best for all centroids in its list. However, some centroids may have been already updated with smaller distances from other red nodes; we take min. That's fine.
Now we need to compute distance between v and centroid c quickly. We have it precomputed in distInfo[v] list; we stored both centroid ID and distance. So we can just iterate.
Complexities: Each query O(log n). Good.
Now let's test with the example:
n=5, edges: 1-2,2-3,2-4,4-5
Queries:
2 1 -> query node 1. isRed[1]=true -> answer 0. Output 0.
2 5 -> query node 5. initially only red 1. Need distance from 5 to nearest red (1). Dist(5,1) =? Path: 5-4-2-1 -> 3 edges => distance 3. So answer should be 3.
1 2 -> paint node 2 red.
2 5 -> query 5: nearest red now? red nodes: 1 and 2. Dist(5,2)=2 (5-4-2), dist(5,1)=3 => min=2. Output 2.
Our algorithm: Initially distInfo built. After initial update with node 1, best for centroids along its path get some values. Then query node 5: not red, iterate over its centroids, compute d+best, take min. Should yield 3. After painting node 2, update best for centroids along node 2's path. Then query 5 gives 2. Works.
Now we need to be careful about the centroid decomposition: we need to ensure that the distances computed are correct for all pairs. Also, we must ensure that we treat the root centroid appropriately.
Let's simulate small tree to ensure centroid decomposition and distances.
Tree: 1-2-3-4-5 (line). For n=5, centroid of whole tree is 3 (since sizes 2 and 2 after removal). So root centroid = 3. distInfo for each node: from centroid 3: distances: 3:0, 2:1, 1:2, 4:1, 5:2. Then we mark dead 3. Components: left subtree containing 1-2, right containing 4-5. For left, find centroid: size 2, centroid can be 2 (or 1? For a tree of two nodes, both are centroids? Usually any node with max subtree size <=1 (since total=2) works. In algorithm, starting from node 2? Actually after removing 3, left component: nodes 1 and 2. We call decompose on neighbor 2 (since v=2). In decompose(2): dfsSize(2) => nodes 2 and 1; subsize[2]=2, subsize[1]=1. Find centroid with total=2: starting at 2, check children (neighbor 1, not dead) subsize[1]=1 <=1? Actually total/2=1, subsize[1]=1 not >1, so centroid stays 2. So centroid=2. Then dfsDist from 2: for nodes in this component (2 and 1): distances: 2:0, 1:1. So for node 1, we add (2,1). Mark dead 2. Then recurse on neighbors of 2 not dead: neighbor 1, so decompose(1). In decompose(1): size 1, centroid=1, dfsDist from 1: distance (1,0) added to node 1. Mark dead 1. No further recursion.
Similarly, right side: decompose(4) -> centroid 4, distances: 4:0,5:1. Then decompose(5): centroid 5, distances:5:0.
Thus for each node, distInfo contains:
- Node1: (3,2), (2,1), (1,0)
- Node2: (3,1), (2,0)
- Node3: (3,0)
- Node4: (3,1), (4,0)
- Node5: (3,2), (4,1), (5,0)
So indeed each node has O(log n) entries.
Now initial red node 1: update best for centroids (3,2), (2,1), (1,0). So best[3]=2, best[2]=1, best[1]=0.
Now query node5 (not red): list (3,2), (4,0), (5,0). For each:
- (3,2): d=2, best[3]=2 => candidate 4
- (4,0): d=0, best[4] is INF (since not updated) => INF
- (5,0): best[5] INF => INF
min = 4? But actual distance from 5 to 1 is 4? Wait, actual distance between 5 and 1 is 4 edges? 5-4-3-2-1 => 4. Yes, answer should be 4. But our algorithm yields 4. But earlier we computed expected 3 for example tree? That's a different tree. For line of 5, initial red 1, query 5 yields 4. That's correct.
Now after painting node 2 red: update best for centroids of node2: (3,1), (2,0). best[3] becomes min(2,1)=1; best[2] becomes min(1,0)=0. Now query node5: candidates:
- (3,2): d+best[3]=2+1=3
- (4,0): INF -> ignore
- (5,0): INF
min=3, which equals distance from 5 to 2? 5-4-3-2 = 3 edges. Yes.
Works.
Now test with the example tree: 1-2-3? Actually example tree: edges: 1-2, 2-3, 2-4, 4-5. This is not a line. Let's compute centroids:
Tree:
1-2-3
|
4
|
5
Total nodes=5. The centroid likely is 2 (since removing 2 leaves subtrees: size1 subtree with node1:1, subtree with node3:1, subtree with nodes4,5:2 => max=2 <=2.5). So root centroid =2. Let's compute manually: Start with decompose(1)? But root centroid should be 2. Our algorithm: start decompose(1) from node1? Actually we need to call decompose(1) on the whole tree. But decompose will compute sizes from that start and find centroid. If we start from node1, will it correctly find centroid 2? Let's simulate: start decompose(1). dfsSize(1) - must explore entire component (no dead nodes). Starting from node1, adjacency: 1-2. So DFS goes: 1->2->3,4->5. subsize[5]=1, subsize[4]=1+subsize[5]=2, subsize[3]=1, subsize[2]=1+subsize[3]+subsize[4]+? Actually subsize[2] = 1 + subsize[3] (1) + subsize[4] (2) = 4? plus itself counts 1 => Actually careful: subsize[2] includes itself: So from 2, children: 1 (parent? but from root 1, 2 is child), 3, 4. So subsize[2]=1 + subsize[3]+subsize[4]? Actually we start at 1, so parent -1. Node1's children: node2. Node2's children: node3, node4 (since node1 is parent). Node4's child: node5. So subsize: node5=1, node4=1+1=2, node3=1, node2=1+1+2=4, node1=1+4=5. So total=5. Then findCentroid starting at node1: check children: node2 subsize=4 >2.5 => move to node2. At node2: check children: node3 subsize=1 <=2.5; node4 subsize=2 <=2.5; also parent node1 is ignored. Also need to check total - subsize[2] = 5-4=1 <=2.5. So centroid =2. Good.
Now after centroid 2, we compute distances from centroid 2 to all nodes: from 2: dist to 2=0, to 1=1, to 3=1, to 4=1, to 5=2. So for each node, we record (2, dist). Then mark dead 2.
Now components after removing 2: Three subtrees: node1 alone, node3 alone, and node4-5 subtree. For each neighbor v (1,3,4) not dead, we call decompose(v). Let's handle node4's subtree: decompose(4). In this component (nodes 4 and 5, as dead 2 blocks). dfsSize(4) -> subsize[4]=2 (4 and 5), subsize[5]=1. findCentroid(4) total=2: check children (neighbor 5) subsize=1 <=1, so centroid=4. Then dfsDist from 4: distances: 4:0, 5:1. Record (4, dist) for nodes 4 and 5. Mark dead 4. Then decompose neighbor 5: component size 1, centroid=5, dfsDist: (5,0) for node5. Mark dead 5.
Similarly, node1's component: decompose(1) -> centroid=1, record (1,0) for node1. node3's component: centroid=3, record (3,0) for node3.
Now final distInfo:
Node1: (2,1), (1,0)
Node2: (2,0)
Node3: (2,1), (3,0)
Node4: (2,1), (4,0)
Node5: (2,2), (4,1), (5,0)
Now initial red node1: update best for (2,1) -> best[2]=1, (1,0) -> best[1]=0.
Now query node5 (type2): distInfo[5] = (2,2), (4,0), (5,0). isRed[5]=false. Compute:
- (2,2): d=2, best[2]=1 => 3
- (4,0): d=0, best[4] = INF => INF
- (5,0): best[5] INF => INF
ans=3. Expected output for first query of node5 was 3? Actually example first type2 on node5 gave 3? Let's see example input:
5 4
edges...
2 1
2 5
1 2
2 5
Output:
0
3
2
So they first query node1 (type2) -> 0, then query node5 -> 3, then paint 2, then query node5 -> 2. So our computed answer for node5 before painting 2 is 3, matches.
After painting node2: update best for node2's centroids: (2,0) -> best[2] becomes min(1,0)=0; (?? node2 may have other centroids? distInfo[2] = (2,0) only? Wait node2's list: only (2,0) because as a centroid, it appears only at its own level? In our decomposition, node2 is centroid root, so it gets only that entry. Actually node2 is centroid, and after removal we don't add other centroids because it's dead; but node2 may also be in components of its ancestors? There are no ancestors because it's root centroid. So its list only contains itself. So update best[2]=0. Then query node5: compute candidates:
- (2,2): d+best[2] = 2+0 =2
- (4,0): INF
- (5,0): INF
ans=2, matches.
Thus algorithm works.
Now implementation details: We need to define INF as something larger than maximum distance (which is < n, so INF = 1e9 is fine).
Now potential pitfalls: The centroid decomposition recursion may cause stack overflow if done recursively for n=1e5, especially with deep recursion depth O(log n) but each decompose call may have its own DFS which is recursive. However, total recursion depth in decompose is O(log n) so fine. But DFS for size and distance could be deep if the tree is a line (depth up to 1e5). That's a problem: recursion depth of DFS may exceed system stack limits (usually around 1e5 it might be borderline). In C++ we can either increase stack size or implement DFS iteratively. For simplicity, we can use recursion with careful optimization and maybe set stack limit via compiler flag. But to be safe, we can implement iterative DFS using stack for size and distance. But since n=1e5 and typical recursion depth of a line tree is 1e5, it's likely to cause stack overflow if we do recursive DFS for size and distance. However, note that we are performing these DFSs only during centroid decomposition. In the worst-case line tree, the centroid decomposition will split the tree roughly in half each time. But the DFS from a centroid will traverse the whole component; that component may be as large as n and depth ~ n. That DFS will be recursive and could cause stack overflow. So we need to avoid deep recursion.
We can implement the DFS for size and distance using an explicit stack (iterative). Or we can increase stack size by using compiler directive. For online judges, sometimes recursion of depth 1e5 is accepted if compiled with certain flags? In many contests (Codeforces), recursion depth of 1e5 is usually too deep and leads to stack overflow unless we use iterative or set stack. Typically, we can use #pragma comment(linker, "/STACK:256000000") on Windows, or use sys.setrecursionlimit in Python. In C++ we can use iterative to be safe.
Alternatively, we can attempt to do recursion but with static array and hope it passes? On Codeforces, many solutions use recursion for DFS in trees up to 2e5 and pass because the default stack might be larger? Actually, typical stack size for C++ on Codeforces is 256MB, so recursion depth of 1e5 might be okay (since each call uses maybe 100 bytes? 1e5*100=10MB, okay). But it's safer to implement iterative.
Given the time, we can implement recursive DFS but with caution. I'll implement recursive but maybe add #pragma GCC optimize("Ofast") and #pragma for stack? I can also convert to iterative for the distance DFS.
Let's design an iterative DFS for computing distances. For size computation, we can also do iterative. However, building iterative with parent tracking is doable.
Simpler: Use recursion but increase stack size via compiler directive: #include <bits/stdc++.h> and then add:
int main() {
// code
}
and compile with -Wl,-stack,10485760? That's not portable. On Codeforces, they might not allow that. However, many contestants just use recursion and it passes for 1e5. For centroid decomposition, we have multiple DFS calls, each may go deep. In a line tree, the first DFS from root centroid (which is near the middle) will have max depth roughly n/2 = 5e4, still high but maybe okay. Subsequent DFS will be smaller. So maximum recursion depth across all calls is about n/2. That may be okay if stack is 8MB? Actually each recursion frame is about maybe 48 bytes? So 5e4*48 = 2.4MB, plus other overhead, likely okay. So recursion should be fine.
But to be extra safe, we can implement iterative for distance and size. However, given time constraints in writing solution, we can use recursion, but ensure we use fast I/O and avoid deep recursion in the worst-case? The worst-case is line tree of 1e5 nodes, first centroid is around 50k, distance DFS from that centroid will travel both sides; the deeper side may be 50k depth (if centroid is near one end? Actually centroid of line is middle, so both sides depth up to 25k? Wait, line of 1e5 nodes: centroid at position ~50k. The distance from centroid to one end is 50k edges? Actually if centroid is at index 50k, then the farthest node is at index 1 or 100k, distance about 50k. The DFS depth will be up to 50k because it's a path. So recursion depth 50k is okay. So fine.
Thus we can implement recursively.
Now we need to store distInfo. We'll use a vector of vectors: vector<vector<pair<int,int>>> distInfo(n+1);. During dfsDist, we push back.
Potential memory: For each node, we have about O(log n) entries, each pair is 8 bytes (two ints) plus vector overhead. So about 1.6e6 * 8 = 12.8 MB plus vector overhead, still okay.
Now implement.
Pseudo-code:
const int N = 100005;
const int INF = 1e9;
int n, m;
vector<int> adj[N];
bool dead[N];
int subsize[N];
vector<pair<int,int>> distInfo[N]; // per node: (centroid, distance)
int best[N]; // for centroids
bool isRed[N];
void dfsSize(int u, int p) {
subsize[u] = 1;
for (int v : adj[u]) {
if (v != p && !dead[v]) {
dfsSize(v, u);
subsize[u] += subsize[v];
}
}
}
void dfsDist(int u, int p, int centroid, int d) {
distInfo[u].push_back({centroid, d});
for (int v : adj[u]) {
if (v != p && !dead[v]) {
dfsDist(v, u, centroid, d+1);
}
}
}
int findCentroid(int u, int p, int total) {
for (int v : adj[u]) {
if (v != p && !dead[v]) {
if (subsize[v] > total/2) {
return findCentroid(v, u, total);
}
}
}
return u;
}
void decompose(int start) {
dfsSize(start, -1);
int c = findCentroid(start, -1, subsize[start]);
// add distances
dfsDist(c, -1, c, 0);
dead[c] = true;
// recurse on subtrees
for (int v : adj[c]) {
if (!dead[v]) {
decompose(v);
}
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
cin >> n >> m;
for (int i=0; i<n-1; ++i) {
int a,b; cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
decompose(1);
fill(best, best+n+1, INF);
isRed[1] = true;
for (auto &p : distInfo[1]) {
best[p.first] = min(best[p.first], p.second);
}
while (m--) {
int t, v; cin >> t >> v;
if (t == 1) {
isRed[v] = true;
for (auto &p : distInfo[v]) {
if (p.second < best[p.first]) best[p.first] = p.second;
}
} else {
if (isRed[v]) {
cout << "0\n";
continue;
}
int ans = INF;
for (auto &p : distInfo[v]) {
ans = min(ans, p.second + best[p.first]);
}
cout << ans << "\n";
}
}
return 0;
}
Check: In type 1, we update best for each centroid. But we should also consider that the node may already be red? Input guarantees it's blue, so okay.
Now we need to confirm that best for centroids not yet updated are INF, and that we never use INF in a way that overflows. min with INF is safe.
Now test on example.
Now think about performance: For each query, we iterate over up to O(log n) entries. With n=1e5, m=1e5, total operations ~1e5*log2(1e5) ~ 1.7e6, fine.
Now we should verify that our centroid decomposition correctly records all ancestor centroids for each node. In our decompose function, we call dfsDist from centroid before marking it dead, and we traverse all nodes in its component. However, note that some nodes may already have been processed in previous centroid's dfsDist? That's intended, because each node gets one entry per level. Since we decompose recursively, each node will be visited in each level where its component's centroid is an ancestor. That's correct.
One nuance: In decompose, after we call dfsDist from centroid c, we mark c dead and then recursively call decompose(v) for each neighbor v. In the recursive calls, they will compute sizes and distances within their components, which do not include c because it's dead. That ensures that each node gets exactly one centroid per level (the centroid of the component it belongs to at that level). So fine.
Now we should also check that for node v, the list distInfo[v] is sorted by level? Not needed.
Now consider initial update: Node 1 is red. But what if node 1 is also a centroid? That's fine. best[1] will be set to 0.
Now query on node 1 after updates: isRed[1] true => output 0. So works.
Now we must ensure that we treat best array for all possible centroid IDs (1..n). Some nodes may never become centroids? Actually every node becomes a centroid at some level? In centroid decomposition, we recursively pick centroids, and eventually each node becomes a centroid when its component size becomes 1. So indeed all nodes will be centroids at some point. So best array for all indices 1..n is used.
Now we should think about memory: distInfo for each node includes entries for all centroids along the path. For node at depth (in centroid tree) up to log n. So okay.
Now we must test on more cases.
Case: n=2, edges: 1-2. Queries: type2 on 2 initially. Expected answer: distance 1 (since node1 red). Let's simulate decomposition:
adj: 1-2.
Call decompose(1): dfsSize(1) -> subsize[1]=2, subsize[2]=1. findCentroid(1) -> check child 2 subsize=1 > total/2? total=2, half=1, subsize[2]=1 not >1, so centroid=1? But check: total - subsize[1] = 2-2=0, fine. So centroid=1. Then dfsDist from 1: distances: (1,0) to node1, (1,1) to node2. Mark dead 1. Then for neighbor 2 not dead, decompose(2): dfsSize(2) -> subsize[2]=1, centroid=2, dfsDist from 2: (2,0) to node2. Mark dead 2. So distInfo:
node1: (1,0)
node2: (1,1), (2,0)
Now initial red node1: update best[1]=0. Query node2: isRed false -> iterate: (1,1) => 1+0=1; (2,0) => 0+best[2] (INF) => INF. ans=1. Good.
Case: After painting node2 red. Then update best: for node2: (1,1) -> best[1]=min(0,1)=0; (2,0) -> best[2]=0. Query node1: isRed true -> 0. Query node2: isRed true -> 0. Works.
Now test scenario where multiple red nodes and query on node that is not red but has two candidates. Should be fine.
Now potential performance issue: In dfsDist, we push back for each node visited. In a large tree, that's O(n log n). That's fine.
Now we need to be careful that we don't exceed time due to large constant factors. The loops are simple.
Now edge case: Could the recursion in decompose cause stack overflow due to many recursive calls? Depth of decompose recursion is O(log n), so fine.
Thus the solution seems solid.
Now we need to output answers for each type 2 query.
Now implement in C++.
Implementation details:
- Use
#include <bits/stdc++.h>.
- Use
using namespace std;.
- Set INF = 1e9.
- Global arrays sized
100005 or dynamic based on n. Since n up to 1e5, static arrays of size 100005+5 is fine.
vector<int> adj[N].
vector<pair<int,int>> distInfo[N] or we can have two vectors: vector<int> cent[N] and vector<int> dist[N], but pair is fine.
bool dead[N] initial false.
int subsize[N].
int best[N].
bool isRed[N].
Now about dfsSize and dfsDist: They will be called many times. Use recursion as described.
Potential bug: In dfsDist, we pass centroid and d. But we are traversing all nodes in the component. However, we must ensure that we do not traverse into nodes that are dead (i.e., previously processed centroids). Since we haven't marked the current centroid dead yet, but all previously processed centroids are already marked dead. So the component consists of nodes that are not dead. In our call from centroid c, we haven't yet marked c dead. So the DFS will include all nodes in the component (including those that will later become centroids in subcomponents). That's correct because we want to record distance from c to all those nodes.
But note: When we later recursively decompose subcomponents, we will call dfsDist for those subcentroids. That will add additional entries. All good.
Now we need to ensure that dfsDist does not cross into other components that are separated by dead nodes. Since the only dead nodes are previous centroids, and they are not connected to the current component except through the current centroid? Actually, after removing previous centroids, the tree is partitioned. The current component is a connected component of non-dead nodes. When we start from c, which is alive, and traverse only non-dead nodes, we stay within the same component. So it's correct.
Now test with a more complex tree to ensure no double counting.
Now about I/O: Use fast I/O.
Now implement.
Now possible improvements: Use reserve for vectors? Not needed.
Now final code.
But before finalizing, consider whether any mistake: In findCentroid, we used subsize[v] > total/2. This works with integer division: For total odd, total/2 floor. Condition > total/2 ensures that no component exceeds half. For example total=5, half=2, so subsize>2 means subsize>=3; that's correct. So okay.
Now one more nuance: In decompose(start), we compute dfsSize(start, -1). But after marking dead some nodes, the component may not be contiguous from start? Actually, the start passed is a node that is in the component (alive). So it's fine.
Now we need to ensure that we don't compute subsize incorrectly due to previous dead nodes. In dfsSize, we skip dead nodes, so it only counts alive nodes. Since the component consists of alive nodes only, and all alive nodes are connected via paths that avoid dead nodes? Actually, when we have dead nodes, the alive nodes form several disconnected components. But when we call decompose(v), we call it for a neighbor v of a dead centroid c. That neighbor v is alive and is in a component that is separate from other components (since c is dead). So when we call dfsSize(v), it will only traverse within that component because the dead centroid blocks. So it's fine.
Now test on line of 100000? Not needed.
Now memory: distInfo total entries about n * (height of centroid tree). Height may be up to ~log2(n) ~ 17, but worst-case for a star tree? Actually centroid decomposition of a star: root centroid is the center, then each leaf becomes centroid of its own component of size 1. So height = 2 (center then leaf). So entries per leaf: center (1) + itself (1) = 2. For center: only itself. So total entries ~ 2n, still O(n). For line tree, height ~ log n, so entries ~ n log n. So worst-case about n * 17 = 1.7e6, fine.
Now code.
Now potential problem: The recursion in dfsDist may be deep for line tree as discussed, but depth <= component size. In a line of 1e5, the first centroid is near middle, so max depth ~ 50k. That's okay. However, subsequent components will be of size ~ 25k, depth 25k, etc. So recursion depth at any time is at most ~50k. Usually stack limit is 8MB, each frame maybe ~48 bytes, so 50k*48 = 2.4MB, okay. But some judges may have smaller stack (like 1MB). But I think Codeforces has 256MB memory and stack limit is usually 256MB? Actually, the stack size for C++ on Codeforces is 256MB? Not sure. Usually, recursion depth of 1e5 is risky but often passes. In centroid decomposition, it's common to use recursion. Many solutions to this problem (CF 342E?) use centroid decomposition with recursion. So it's fine.
Now we also need to consider that we have multiple DFS calls; but they are not nested deeply. So it's okay.
Now confirm that the algorithm is known: This problem is Codeforces Round #342 (Div. 2) problem E: "Xenia and Tree". Actually that problem has both painting and queries. The typical solution uses centroid decomposition or sqrt decomposition. So our solution matches.
Now we need to ensure to set isRed[1] = true initially. Also we might set best for centroid 1 if 1 becomes a centroid? Actually we update based on distInfo[1]. That includes all centroids on path. So best for centroid 1 will be set to 0 if 1 is a centroid; otherwise if 1 is not a centroid, its own centroid list does not include 1. But there is a centroid that is exactly node 1 at some level? Node 1 may become a centroid later if its component size becomes 1. So yes, at some point node 1 will be a centroid (when its component is just itself). Then distInfo[1] will include (1,0). So best[1] gets 0. That's fine. But if node 1 is not a centroid initially (i.e., it is not the root centroid), it will still have a centroid entry for the root centroid and others, and the best for those centroids will be set to distances. The query for node1 via centroids might give non-zero? But since isRed[1]=true, we output 0 directly, so no issue. For other nodes, the nearest red node could be node1, and the distance will be computed via centroids correctly.
Now we should check that for node1 (red) but we are not updating best for centroids that are not ancestors of node1? That's fine because we won't query them from other nodes if they are not common ancestors? Actually, for a node v, we consider ancestors of v. If node1 is red, then for any v, there is some common ancestor centroid c that is ancestor of both. So best[c] gets updated with distance from node1 to c, and then v gets candidate via c. So all good.
Now we should also consider that after many red nodes, best values may become small. The min operation is constant.
Now finalize code.
Potential improvements: Use int for distances, as tree distances up to n.
Now check with sample.
Input:
5 4
1 2
2 3
2 4
4 5
2 1
2 5
1 2
2 5
Our code:
distInfo built as earlier.
Processing:
Initial red node1: best updates: centroid2? Actually node1's list: (2,1), (1,0). So best[2]=1, best[1]=0.
Query: 2 1 -> isRed[1]=true -> output 0.
Query: 2 5 -> isRed[5]=false -> compute: (2,2): 2+1=3, (4,0):0+INF=INF, (5,0):0+INF=INF -> ans=3 -> output 3.
Update: 1 2 -> isRed[2]=true -> update best: node2's list: (2,0) -> best[2]=min(1,0)=0.
Query: 2 5 -> ans = min(2+0=2, INF, INF)=2 -> output 2.
Matches.
Now we should test with additional cases.
Case: n=3, edges:1-2,2-3. Queries: type2 3, type1 3, type2 2. Initially red1.
distInfo building: centroid root =2? Let's compute: centroid of 3 nodes line is 2. So distInfo:
1: (2,1), (1,0) (since after removing 2, component with 1 gives centroid 1)
2: (2,0)
3: (2,1), (3,0)
Init: update node1: best[2]=1, best[1]=0.
Query 3: isRed false -> candidates: (2,1): 1+1=2, (3,0):0+INF=INF -> ans=2. Dist(3,1)=2, correct.
Paint 3 red: update node3: (2,1) -> best[2]=min(1,1)=1; (3,0) -> best[3]=0.
Query 2: isRed false? Actually 2 not red (unless painted). Candidates: (2,0): 0+best[2]=0+1=1? But distance to nearest red: red nodes are 1 and 3. Dist(2,1)=1, dist(2,3)=1, so answer 1. Our candidate gives 1? Wait (2,0) + best[2] = 0+1=1. Good. Also (??? does 2 have other centroids? It may have only (2,0). So ans=1. Correct.
Now test case where query node is red but we forgot to set isRed? We do set.
Now one more nuance: When painting a node red, we update best for all centroids. But later we might query a node that is also red? We check isRed first and output 0. So even if best values are not updated to reflect zero distance from that node to itself? Not needed.
Now consider if we paint a node red and later that node becomes centroid? It already is a centroid (since all nodes become centroids at some level). So best[that centroid] gets updated to 0. That ensures that for queries on nodes in that centroid's subtree, the distance to this red node can be computed via that centroid. But if the red node is not the centroid for that level, there will be higher level centroids covering it.
Now we should also verify that we are not double counting for queries: For query node v, we may consider centroid c where best[c] is from a red node that is not in the same component as v? But c is an ancestor of v, meaning v is in the subtree of c in centroid tree. The red nodes that contributed to best[c] are from that subtree (since we only update best[c] with nodes from that component). Actually when we update best[c] using a red node u, we only do it if c is an ancestor of u (i.e., u is in c's component). Since we update using u's list, which includes all centroids that are ancestors of u. That means for any centroid c in u's list, u is in the subtree of c (or the component). Thus best[c] stores min distance from red nodes that are in c's subtree. For query v, we consider centroids that are ancestors of v. For a given centroid c that is ancestor of v, the red nodes that contributed to best[c] are in c's subtree. v is also in c's subtree, so they are in the same overall region. So it's consistent. There is no cross contamination.
Now one more check: Could there be a case where the nearest red node is not captured because the LCA centroid in centroid tree is not on v's ancestor list? Actually LCA of v and u is always an ancestor of v (and u). So it is included.
Now we need to be careful about the definition of ancestor in centroid tree: The root centroid is ancestor of all nodes. The parent relation: For a node v, the list of centroids we stored are exactly those centroids that are ancestors of v in centroid tree. Because we add centroid c to v's list only when v is in the component of c (i.e., v belongs to the subtree of c). So yes.
Now we are good.
Now we can implement.
But before finalizing, we should think about alternative simpler solution using sqrt decomposition and multi-source BFS: Since we have only additions, we can maintain an array dist which is the current distance to nearest red. Initially, we can compute distances from node 1 via BFS (or set INF except node1=0). Then when we add a red node, we can perform a BFS from that node, but only if the number of red nodes is less than sqrt(m) or something, and for queries we compute answer by taking min of dist array and distances to recently added red nodes. That's also common. But centroid decomposition is more straightforward to implement once known.
Given that we already derived the centroid approach, we'll go with it.
Now code.
Potential pitfalls: In decompose, we call dfsDist(c, -1, c, 0). However, note that dfsDist will also traverse into nodes that are dead? They aren't dead yet. But we must ensure that we don't traverse into nodes that are not part of the component because they are separated by dead nodes? The component is exactly the set of nodes reachable from c without passing through dead nodes. Since no other dead nodes are present (except previous centroids which are not connected to c except through other dead nodes?), Actually after previous decompositions, there are dead nodes. The current component was formed by starting from a node that is alive and part of this component. The centroid c is alive and the component is connected via alive nodes only. So any neighbor of c that is alive leads into a subtree that is part of the component. Neighbors that are dead (like previous centroids) are not traversed because we check !dead[v] in dfsDist. So it's correct.
Now one more check: In decompose, after marking c dead, we loop over neighbors and call decompose(v). But what if some neighbor v is dead? It won't be because we only iterate over adjacency and check if (!dead[v]). That's fine.
Now about the recursion in decompose: In a star tree, the center is centroid, then we recursively call decompose on each leaf. The number of recursive calls is n, but depth is 2. So fine.
Now we need to ensure that the total calls to dfsSize and dfsDist are O(n log n). Each node is visited in dfsSize for each level when it is in the component being sized. That's O(n log n). Same for dfsDist.
Now implement.
Now code with fast I/O:
#define FAST_IO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
Now final code.
We should also consider using int for loop indices.
Now let's think about potential bug in findCentroid: Suppose we have a component of size 2: nodes A-B. Starting from A, subsize[A]=2, subsize[B]=1 (if B is child). findCentroid(A) checks children: B subsize=1, total/2=1, so not >, so returns A. But is A a centroid? For component of 2 nodes, either node can be centroid because removing A leaves one component of size 1 (<=1). So A is fine. If we had started from B, would it return B? Possibly, but we start from the node passed (which is the root of the DFS). In our decompose, we call decompose(start) where start is some node in the component. This may not be the "best" starting point, but the centroid finding algorithm will still find a centroid because it moves to children if they exceed half. However, if the centroid is actually the node that is not in the child direction, but in the parent direction relative to start, could it fail? As argued earlier, the algorithm works because if the centroid lies in the parent direction, then the subtree that includes the parent is large, but that means there is a child (the one that leads to the parent) that has size > total/2? But in the DFS tree from start, the parent direction is not considered a child; it's the parent of the root. So if the centroid is in the parent direction, then the start node's size includes the whole tree, and the condition total - subsize[start] > total/2? But we don't check that. However, if the centroid is in the parent direction, then the start node itself is not centroid because the component of the parent direction is large. In that case, there must exist a child of start that contains that large component? Actually, consider a tree where start is a leaf, and the centroid is somewhere near the center. The leaf's only neighbor is its parent. In the DFS from leaf, the parent is considered a child because the leaf is root of DFS with parent -1. So leaf's child is the parent. So we do check that child. And if the centroid is up that direction, that child's subtree size will be total-1, which is > total/2. So algorithm moves to that child. So it will move up. So it works. Indeed, in the earlier example of star with leaf as start, we moved to center. So the algorithm works.
Thus findCentroid is fine.
Now we might also consider using std::vector::reserve for distInfo to avoid reallocation. Not necessary.
Now final code.
But wait, there is a known issue: In dfsDist, we call dfsDist(v, u, centroid, d+1). However, if the graph is deep, recursion depth may be large, but acceptable.
Now we could also compress the pair<int,int> into two arrays to reduce memory, but it's fine.
Now compile and test with sample.
Now I'll produce the final answer.
But also note: The problem says "paint a specified blue node in red". So it's guaranteed that for type1 queries, node is blue. So we don't need to check if already red.
Now we may also consider using std::vector<std::array<int,2>> but pair is fine.
Now final answer.
However, I recall that in some implementations of centroid decomposition for this problem, they also maintain a ans variable for each node but here we compute on query. Good.
Now produce final code.
Before final, let's double-check the update for type 1: We update best for centroids on the node's list. But is there any scenario where we need to update best for centroids that are not ancestors of the node? No.
Now implement.
Potential micro-optimizations: Use local references for vectors inside loops to avoid copying. But fine.
Now think about best array: We will use int best[N]. Initialize with INF. After many updates, best values become small. When we compute ans = min(ans, d + best[c]), we must ensure best[c] is not INF; but if INF, d+INF may overflow? INF is 1e9, d up to 1e5, sum up to ~1e9+1e5, still within int range (2e9). But we may want to guard: if best[c] == INF, skip. But not necessary, we can still compute min but INF+something may exceed 2e9 and cause overflow? int max is about 2.147e9. 1e9+1e5 = 1,000,100,000 which is less than 2.147e9. So safe. But to be safe, we can skip when best[c] == INF. I'll add a condition.
Now final code.
Let's write final solution. ```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
const int INF = 1e9;
int n, m;
vector adj[N];
bool dead[N];
int subsize[N];
vector<pair<int, int>> distInfo[N]; // for each node: list of (centroid, distance)
int best[N]; // for each centroid: min distance to a red node in its region
bool isRed[N];
// compute subtree sizes (ignoring dead nodes)
void dfsSize(int u, int p) {
subsize[u] = 1;
for (int v : adj[u]) {
if (v != p && !dead[v]) {
dfsSize(v, u);
subsize[u] += subsize[v];
}
}
}
// find centroid of current component (total size = total)
int findCentroid(int u, int p, int total) {
for (int v : adj[u]) {
if (v != p && !dead[v]) {
if (subsize[v] > total / 2) {
return findCentroid(v, u, total);
}
}
}
return u;
}
// traverse component from centroid, record distances to this centroid
void dfsDist(int u, int p, int centroid, int d) {
distInfo[u].push_back({centroid, d});
for (int v : adj[u]) {
if (v != p && !dead[v]) {
dfsDist(v, u, centroid, d + 1);
}
}
}
// centroid decomposition
void decompose(int start) {
dfsSize(start, -1);
int c = findCentroid(start, -1, subsize[start]);
// record distances to this centroid for all nodes in the component
dfsDist(c, -1, c, 0);
dead[c] = true;
// recurse on each neighbouring component
for (int v : adj[c]) {
if (!dead[v]) {
decompose(v);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
for (int i = 0; i < n - 1; ++i) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
// build centroid decomposition
decompose(1);
// initialize
fill(best, best + n + 1, INF);
isRed[1] = true;
for (auto &p : distInfo[1]) {
best[p.first] = min(best[p.first], p.second);
}
while (m--) {
int t, v;
cin >> t >> v;
if (t == 1) {
// paint blue node v red
isRed[v] = true;
for (auto &p : distInfo[v]) {
if (p.second < best[p.first]) {
best[p.first] = p.second;
}
}
} else {
// query distance to nearest red node
if (isRed[v]) {
cout << "0\n";
continue;
}
int ans = INF;
for (auto &p : distInfo[v]) {
if (best[p.first] != INF) {
ans = min(ans, p.second + best[p.first]);
}
}
cout << ans << "\n";
}
}
return 0;
}