Official

B - Reversible Cards Editorial by evima


Consider the graph \(G\) where there is a vertex for each color and an edge for each card. Then, we can rephrase the problem as follows:

  • For each edge in \(G\), we can light one of the endpoints. At most how many vertices can be lit?

We can handle each connected component in \(G\) separately, so let us consider just one connected component.

  • If the connected component is a tree, we can light \(n-1\) vertices, where \(n\) is the number of vertices in the connected component. We can do this as follows: let us choose some vertex and make it the root, then light the “younger” vertex to light \(n-1\) vertices other than the root. Since the graph is a tree, it has only \(n-1\) edges, so we cannot light more vertices.
  • If the connected component is not a tree, we can light all \(n\) vertices. We can do this as follows: let us choose some spanning tree and specify as the root one of the endpoints of an edge \(e\) that is not in the spanning tree. Then, do the thing we did where the graph was a tree, and use \(e\) to light the root.

Thus, the problem boils down to determining whether each connected component in \(T\) is a tree. We can do it in linear time with respect to the number of vertices and edges in \(G\), with depth-first search, for example.

posted:
last update: