Editorial for COCI '16 Contest 5 #6 Strelice
Submitting an official solution before solving the problem yourself is a bannable offence.
Let's construct a graph where the nodes are the fields of the board, and the edges are obtained by connecting two nodes of each arrow that is not in the last column, using a directed edge. Since each node has a degree of at most , the obtained graph consists of two different types of components:
- Directed tree
- Cycle with "branches" leading to it
Each path from the first column to the last column is actually a path from a tree node to the root of that same tree. Let's mark the nodes in the first column as "special". Now the task is actually to color the nodes of the tree so that each path from a special node to the root contains exactly one colored node. Let's apply a trick: we can add an auxiliary node to the graph and an edge from each root to that auxiliary node. Now we have exactly
tree in the graph and its solution is checked using dynamic programming.
Let's calculate the value of function that returns whether we can color all subtrees of node
from its
child onwards. The crucial part is to determine how many nodes we will color in the
subtree. If we color exactly
nodes, the solution exists if both values of
and
are equal to
. In the end, we make sure that we can arbitrarily color the nodes in the components that lead to cycles. If we iterate over all possible
, the complexity of this algorithm is
.
In order to speed up the solution, we can use bitmasks. Let's denote the bitmask that contains bit in the
position with
. Additionally, we denote with
that same mask with the first
bits in reverse (the
element of
is the
of
). Now
. We leave it as an exercise for the reader the proof of the correctness of this optimization that enables the speed-up of the aforementioned dynamic programming approach to
.
Comments