Official

I - Add One Edge 2 Editorial by en_translator


Let us rephrase the conditions in the problem statement.

If you add an edge connecting vertices \(u\) and \(v\), the vertices on the \(u-v\) path are contained in the vertices. Thus, the problem is rephrased as follows: find the number of simple paths containing three or more vertices, such that the degrees of the endpoints are \(2\), and those of the others are \(3\).

We will solve this rephrased problem using DP (Dynamic Programming) on tree. Pick an arbitrary vertex to view the tree as a rooted tree.

Consider the LCA (Lowest Common Ancestor) of the endpoints of the path to be counted. Then the LCA coincides with one of the endpoints, or one of the other vertices in the path.

First, consider the case where an endpoint coincides with the LCA. Let \(u\) be the LCA, then the sought number of paths equals the number of vertices of degree \(2\) contained in the subtree of \(u\), that are reachable from \(u\) via one or more vertices of degree \(3\). This can be counted bottom-up with tree DP.

Next, consider the case where the LCA does not coincide with the endpoints. Let \(u\) be the LCA, and \(S\) be the set of vertices of degree \(2\) contained in the subtree of \(u\), that are reachable from \(u\) via one or more vertices of degree \(3\). Then the sought count equals the number of ways to choose two vertices from \(u\) such that the LCA of the chosen two vertices coincides with \(u\).

This count equals the number of ways to pick a vertex of each of two subtrees, which in turn are chosen from the subtrees that are obtained by splitting the subtree of \(u\) by removing the \(u\) itself. It can also be counted with similar DP.

The complexity is \(\mathrm{O}(N)\).

posted:
last update: