Official

E - A Gift From the Stars Editorial by en_translator


The leaves of \(T\) are leaves of initial stars, and those vertices distant by at most two from it belong to the same star. Thus, the following algorithm is possible.

  • Choose a leaf of \(T\).
  • Count the number of vertices distant by at most two from it (including itself). If there are \(x\) of them, they form a level-\((x-1)\) star.
  • Remove the counted vertices and adjacent edges from \(T\).

After you repeat this until no vertices remain in \(T\), you obtain the answer. With an appropriate implementation, it works in a total of \(\mathrm{O}(N)\) time, but the implementation is a bit complicated. We describe a simpler implementation with some observations.

The following lemma holds.

  • In an original star, let us call the non-leaf vertex the center. In \(T\), the distance between centers is always a multiple of \(3\), and that between a center and a leaf is always a non-multiple of \(3\).

This can be shown by induction. With this lemma, we can come up with the following algorithm:

  • Choose a vertex from \(T\) that was the center of an original star. You can do so by choosing the vertex adjacent to a leaf.
  • Find the shortest distance of each vertex from the chosen vertex.
  • For each vertex whose shortest distance is a multiple of \(3\), add the degree of that vertex to \(L\).

This algorithm works in a total of \(\mathrm{O}(N)\) times, and requires a simple algorithm like BFS (Breadth-First Search) or DFS (Depth-First Search).

posted:
last update: