公式

B - Red and Blue Spanning Tree 解説 by evima


We will construct a spanning tree that satisfies the conditions as follows.

  1. Construct a forest satisfying the condition on color denoted by \(s_1s_2\ldots s_N\).
  2. Add edges to the above forest to form a tree.

The first step is essential, since the second can be done greedily or whatever.

Classify the edges into the following three types.

  1. Edges with both \(s_{a_i} = c_i\) and \(s_{b_i}=c_i\)
  2. Edges with exactly one of \(s_{a_i} = c_i\) and \(s_{b_i}=c_i\)
  3. Edges with \(s_{a_i} \neq c_i\) and \(s_{b_i}\neq c_i\)

Since type-\(3\) edges are not useful in the first step, we only consider type-\(1\) and type-\(2\) edges.

When some type-\(1\) edges are chosen for the spanning tree so that no cycle is formed, we consider whether some type-\(2\) edges can be chosen to construct a forest that satisfies the condition. Let \(X\) be the set of vertices for which the condition is satisfied by the chosen type-\(1\) edges. If you can repeat the following operation to obtain \(X = \{1,2,\ldots,N\}\), then you have constructed a desired forest.

  • Choose for the spanning tree a type-\(2\) edge such that the endpoint not satisfying the condition is in \(X\) and the endpoint satisfying the condition is not in \(X\), and add the latter endpoint to \(X\).

(When an edge is chosen by the above operation, the endpoint satisfying the condition is an isolated point, so no cycle is formed.) On the other hand, if there is no more edge to choose from before obtaining \(X = \{1,2,\ldots,N\}\), then either there is no edge of the specified color for some vertex to begin with, or a cycle is bound to be formed because you need as many edges as vertices to satisfy the condition for all vertices in a connected component where only type-\(2\) edges are considered. Therefore, the above method can determine whether a forest can be constructed with type-\(2\) edges to satisfy the condition.
Also, there is no disadvantage in having more elements of \(X\) using type-\(1\) edges, so we only need to consider choosing as many type-\(1\) edges as possible without forming a cycle.

投稿日時:
最終更新: