公式

G - Coloring Tree 解説 by kenken714


Let \(S_v\) denote the minimum number of colors required to paint the subtree rooted at vertex \(v\) while satisfying the given conditions.

Suppose the children of vertex \(v\) are \(w_1, w_2, \ldots, w_k\) . If the minimum number of colors required for each child \(S_{w_i}\) \((1 \leq i \leq k)\) is already determined, we can compute \(S_v\) as follows:

If \(v\) has two or more children, let \(S_1\) and \(S_2\) represent the largest and second-largest values among \(S_{w_i}\) (\(1 \leq i \leq k\)), respectively. Then, \(S_v = \max(S_1, S_2 + 1)\).
If \(v\) is a leaf, \(S_v = 1\).
If \(v\) has only one child, \(S_v = S_{w_1}\).

Outline of the proof

Case 1: \(v\) is a leaf

Since there is only one vertex in the subtree, only one color is required. Thus, \(S_v = 1\).

Case 2: \(v\) has only one child

When considering the subtree rooted at the child \(w_1\) of \(v\), there are no two distinct vertices \(a\) and \(b\) such that \(\mathrm{lca}(a, b) = v\).
Therefore, the color assigned to \(v\) does not affect whether the conditions of the problem are satisfied. Consequently, \(S_v = S_{w_1}\).

Case 3: \(v\) has two or more children

Let \(S_1\) and \(S_2\) denote the largest and second-largest values among \(S_{w_i}\) (\(1 \leq i \leq k\)), respectively.

Case 3.1: \(S_1 > S_2\)

To satisfy the conditions, at least \(S_1\) colors are required. Let \(c_1, c_2, \ldots, c_{S_1}\) be the colors used in the subtree corresponding to \(S_1\). By reusing \(c_1, c_2, \ldots, c_{S_1 - 1}\) for the other subtrees and assigning \(c_{S_1}\) to \(v\), the subtree rooted at \(v\) can be painted using exactly \(S_1\) colors. Hence, \(S_v = S_1\).


Case 3.2: \(S_1 = S_2\)

In this case, we also have \(S_v \geq S_1\). Assume \(S_v = S_1\). Let \(T_1\) and \(T_2\) be the subtrees corresponding to \(S_1\) and \(S_2\), respectively. The set of colors used in \(T_1\) and \(T_2\) must be the same, say \(C\). If \(v\) is painted with a color \(c_v \in C\), then there exist vertices \(w_1\) and \(w_2\) in \(T_1\) and \(T_2\), respectively, such that \(\mathrm{lca}(w_1, w_2) = v\) and \(c_{w_1} = c_{w_2} = c_v\), violating the conditions. Thus, \(S_v \geq S_1 + 1\).

By assigning a new color \(c_{S_1 + 1}\) to \(v\), the subtree rooted at \(v\) can be painted with \(S_1 + 1\) colors. Hence, \(S_v = S_1 + 1\).


Combining the results, \(S_v = \max(S_1, S_2 + 1)\) holds.

By performing DP from the leaves to the root, the answer for the entire tree can be computed in \(O(N)\) time.

Sample Solution (C++)

投稿日時:
最終更新: