Official

G - Farthest City Editorial by en_translator


This problem is easy to understand if you know the concept called “BFS (Breadth-First Search) Tree.” The concept also appears in a past problem in ABC (AtCoder Beginner Contest), so if you have never heard of, do learn it.


Let \(d_u\) be the shortest distance from vertex \(1\) to vertex \(u\).
\(d_1\) is always \(0\). When the values \(d_2, \dots, d_N\) are fixed, “\(d_u\) is the shortest distance from vertex \(1\) to vertex \(u\)” if and only if:

  • for all \(u = 2, \dots, N\), there exists at least one edge connecting vertices \(u\) and \(v\) such that \(d_v + 1 = d_u\); and
  • there is no edge such that \(|d_u - d_v| \geq 2\).

It is sufficient to count the number of sets of edges that satisfy the conditions above for all tuples \((d_1, \dots, d_N)\) such that \(d_N\) is smaller than \(d_1, \dots\), and \(d_{N-1}\).
The pairs of conforming \((d_1, \dots, d_N)\) and set of edges can be constructed by the following procedure without duplicates:

  • Initialize with \(d_1 = 0, d_2 = \dots = d_N = \infty\), and an integer \(n\) with \(n = 0\).
  • Repeat the following steps while there exists \(u\) such that \(u \neq N\) and \(d_u = \infty\):
    • Choose one or more \(u\)’s such that \(u \neq N\) and \(d_u = \infty\), denoting them by \(u_1, \dots\), and \(u_k\).
    • For each \(u_i\), choose one or more \(v\)’s such that \(d_v = n\); for each of them, add an edge \((v, u_i)\). Replace the value of \(d_{u_i}\) with \(n+1\).
    • Choose zero or more \((i, j)\)’s such that \(1 \leq i \lt j \leq k\); for each of them, add an edge \((u_i, u_j)\).
    • Increment \(n\) by \(1\).
  • For each \(u_i\), choose one or more \(v\)’s such that \(d_v = n\); for each of them, add an edge \((v, N)\). Replace the value \(d_{N}\) with \((n+1)\).

The procedure above can be boiled down to the following Dynamic Programming (DP):

  • \(\mathrm{dp}_{n, k} :=\) “the number of ways to have \(n\) \(u\)’s such that \(d_u \neq \infty\), \(k\) of which takes the maximum \(d_u\).”

Since there are \(O(N^2)\) states, and each transition costs \(O(N)\) time, the problem has been solved in a total of \(O(N^3)\) time.

posted:
last update: