Narfouz in the Center#12438

Narfouz in the Center (Editorial)

Let's root the tree at node .

We define the following DP arrays:

\text{downDepth}_x: the maximum depth from to a leaf in its subtree.

\text{downDiam}_x: the diameter (in number of nodes) of the subtree rooted at .

We compute them as:

\text{downDepth}_x = 1 + \max_{y \in \text{children}(x)} \text{downDepth}_y
\text{downDiam}_x = \max\left( \max_{y \in \text{children}(x)} \text{downDiam}_y,\; 1 + \text{largest two values of } \text{downDepth}_y \right)

Now define the upward DP:

\text{upDepth}_x: the maximum depth starting from going outside its subtree.

\text{upDiam}_x: the diameter of the tree after removing the subtree of .


To compute \text{upDepth}_x (where p = \text{parent}(x)):

\text{upDepth}_x = 1 + \max\left( \text{upDepth}_p,\; \max_{y \in \text{children}(p),\, y \neq x} \text{downDepth}_y \right)

To compute \text{upDiam}_x, we take the maximum of:

\text{upDiam}_p
\max_{y \in \text{children}(p),\, y \neq x} \text{downDiam}_y
1 + \text{largest two values among } \left\{ \text{upDepth}_p \right\} \cup \left\{ \text{downDepth}_y : y \in \text{children}(p),\, y \neq x \right\}

Finally, for a node , after removing it, each component corresponds to:

For each component, we compute its diameter and count centers:

\text{centers}(d) = \begin{cases} 1 & \text{if } d \text{ is odd} \\ 2 & \text{if } d \text{ is even} \end{cases}

Thus,

\text{ans}_v = \sum_{\text{children } u \text{ of } v} \text{centers}(\text{downDiam}_u) \;+\; \text{centers}(\text{upDiam}_v)

Time complexity: