D - Tree and Intervals Editorial by evima
Among the edges incident to vertex \(i\), let \(l_i\) be the number of edges whose other endpoint is less than \(i\), and \(r_i\) be the number of the other edges. Then, we have \(x_i = \sum_{j=1}^{i} (r_j - l_j)\).
First, consider the necessary conditions for the tree corresponding to \(l_1,r_1,l_2,r_2,\ldots,l_N,r_N\) to exist:
- Obviously, \(l_1 = 0\), \(r_N = 0\), and \(\sum (r_j - l_j) = 0\).
- For each \(i\), at least one of \(l_i \neq 0\) or \(r_i \neq 0\) must hold.
- The forest induced by vertices up to \(i\) has \(i\) vertices and \(\sum l_j\) edges, so the number of connected components is \(i - \sum l_j\), which must be positive. Furthermore, when \(i < N\), the number of edges connecting vertices up to \(i\) with vertices greater than \(i\) is \(\sum (r_j - l_j)\), which must be at least the number of connected components (otherwise, there would be isolated connected components). In summary, we need \(1 \leq i - \sum l_j \leq \sum (r_j - l_j)\).
- If \(i = N - 1\) in 3., the number of edges connecting vertices up to \(i\) must equal the number of connected components, so we need \(N - 1 - \sum_{j=1}^{N - 1} l_j = \sum_{j=1}^{N - 1} (r_j - l_j)\).
Also, the above four conditions are sufficient. If we proceed in order of \(i = 1, 2, \ldots, N\), connecting \(l_i\) edges to existing connected components, and if there exists a connected component with at least two unused edges, we can first connect to it, maintaining the state that each connected component has unused edges while the conditions are satisfied.
Returning to the original problem of counting possible \(x_i\), the second condition is \(1 \leq i - \sum_{j=1}^{i} l_j \leq x_i\) for each \(i\). Here, we can freely increase \(l_i\) while keeping \(x_i = \sum (r_j - l_j)\) unchanged (increasing \(r_i\) at the same time; this does not violate any conditions), so it is convenient to consider the minimum possible \(\sum l_j\). By defining \(\mathrm{dp}_{i,j,k}\) as “the number of ways where \(x_i = j\) and the minimum value of \(\sum_{t=1}^{i} l_t\) is \(k\)”, and performing transitions using cumulative sums while considering the appropriate conditions, we can solve this problem in \(\mathrm{O}(N^3)\) time.
posted:
last update: