Official

F - Paint Tree Editorial by evima


Let \(D\) be the diameter of the tree and \(x, y\) be the endpoints of the diameter.

If \(x\) and \(y\) are of the same color, the niceness is obviously \(D\). Below, we only consider the case \(x\) is white and \(y\) is black. An important fact is that there is a white vertex whose distance from \(x\) is \(X\). The same goes for \(y\) and \(Y\). We can prove this from the fact that \(x\) and \(y\) are the endpoints of the diameter.

Thus, the distances from \(x\) and \(y\) only matter; the distances between the other vertices do not matter. From here, we can see the following: if there is a vertex whose distances from \(x\) and \(y\) are both greater than \(d\), there is no way of painting the tree with niceness at most \(d\); otherwise, there are \(2^{k}\) such ways, where \(k\) is the number of vertices whose distances from \(x\) and \(y\) are both at most \(d\).

Using these, we can find the total niceness of all ways of painting the tree. It can be done in \(O(N)\) time, which is fast enough.

posted:
last update: