A - Tree Contraction Sequence 解説 by evima 印刷ページ
Let \(T\) denote the tree given in the input.
We will collect conditions of the form “vertex \(v\) must be operated on after vertex \(u\)”.
First, for any two vertices \(u,v\), let us find a necessary and sufficient condition for \(v\) to appear after \(u\) in the final sequence. Let \(w\) be the LCA of \(u\) and \(v\). In general, for a vertex \(x\) and its ancestor \(w\), let \(M(x,w)\) be the time at which all vertices on the \(x-w\) path except \(w\) have been operated on. The operations are performed at times \(1,2,\ldots,N-1\), and we define \(M(x,w)=0\) when \(x=w\). \(M(x,w)\) is the time at which vertices \(x\) and \(w\) are first merged into the same vertex. Thus, \(u\) comes before \(v\) in the final sequence if and only if \(M(u,w)<M(v,w)\).
These conditions can be expressed collectively as a rooted forest. That is, there exists a rooted forest on the vertex set \(\{2,3,\ldots,N\}\) such that the final sequence is \((1,2,\ldots,N)\) if and only if, for every parent-child pair in this forest, the child is operated on before the parent. We prove this fact together with an algorithm for constructing the forest.
Let \(F\) denote the forest representing the conditions on the order of operations.
We process vertices \(2,3,\ldots,N\) in this order. Suppose that vertices up to \(v\) have been processed.
Consider adding vertex \(v+1\). The case \(v=P_{v+1}\) is trivial, so consider the case \(v>P_{v+1}\). Let \(w\) be the LCA of \(v\) and \(P_{v+1}\) in \(T\). Since \(P_{v+1}<v\), the conditions so far imply \(M(P_{v+1},w)<M(v,w)\). Furthermore, \(v\) comes before \(v+1\) if and only if \(M(v,w)<M(v+1,w)\). This amounts to the constraint that \(v+1\) must be operated on later than all vertices on the \(v-w\) path except \(w\).
Therefore, we can add edges to \(v+1\) from those vertices on the \(v-w\) path, excluding \(w\), that are roots of \(F\). Conversely, adding just these edges is sufficient to update \(F\). This follows from the following two facts.
- After processing up to \(v\), all vertices (numbered at most \(v\)) that are roots of \(F\) lie on the path from vertex \(1\) to \(v\) in \(T\).
- Consider a vertex \(x\) on the path from \(1\) to \(v\) that is not a root of \(F\). If \(y\) is the root of \(x\) in \(F\), then \(y\) lies on the \(v-x\) path.
These facts can be verified by induction.
Once the forest is obtained, the counting is easy.
The forest can be computed quickly by maintaining a union-find structure that connects each vertex \(v\) that is not a root of \(F\) with \(P_{v}\).
The time complexity is \(O(N \alpha (N))\).
投稿日時:
最終更新: