公式

F - Sum of Mex 解説 by en_translator


Let \(c_k\) be the number of pairs \((i,j)\) with \(f(i,j) \geq k\). Then the number of pairs \((i,j)\) with \(f(i,j) = k\) equals \(c_k-c_{k+1}\). Thus, the sought answer is

\[ \begin{aligned} &\phantom{=}\sum_{k\geq 1} k(c_k-c_{k+1})\\ &=\sum_{k\geq 1} kc_k-\sum_{k\geq 1} (k-1)c_k\\ &=\sum_{k\geq 1} c_k, \end{aligned} \]

which is merely the sum of \(c\). Now let us consider how to find the values \(c_1,c_2,\ldots,c_N\) in this order.

First, when \(f(i,j) \geq k\), it is necessary that the path from vertex \(i\) to vertex \(j\) contains all of vertices \(0,1,\ldots,k-1\) (actually, it is sufficient too). When there is a path containing all of vertices \(0,1,\ldots,k-1\), there exist two vertices \(x_k,y_k\) such that the following two conditions are equivalent:

  • The path contains all of vertices \(0,1,\ldots,k-1\).
  • The path contains the path from vertex \(x_k\) to vertex \(y_k\).

Consider how we can track these \(x_k\) and \(y_k\) incrementally, in ascending order of \(k\).

For \(k=0\), obviously \(x_0=y_0=0\).

Given \(x_{k-1}\) and \(y_{k-1}\), one can find \(x_k\) and \(y_k\) as follows:

  • If the path between vertices \(x_{k-1}\) and \(k\) contains vertex \(y_{k-1}\), then \((x_k,y_k)=(x_{k-1},k)\).
  • If the path between vertices \(k\) and \(y_{k-1}\) contains vertex \(x_{k-1}\), then \((x_k,y_k)=(k,y_{k-1})\).
  • If neither of the conditions above is satisfied, then no pair of \(x_k\) and \(y_k\) satisfies the condition. IN other words, there is no path containing all of vertices \(0,1,\ldots,k-1\).

One can can determine if a path contains a vertex in \(O(\log N)\) time, using algorithms such as LCA (Lowest Common Ancestor).

The problem can be solved by appropriately implementing the algorithm above. The computational complexity is \(O(N \log N)\).

投稿日時:
最終更新: