Editorial for COCI '13 Contest 2 #5 Paleta
Submitting an official solution before solving the problem yourself is a bannable offence.
If we represent the coloring book as a graph, the images act as the nodes and two nodes are connected with an edge if they cannot be colored in the same color.
Firstly, solve the case when all the input numbers are different. Then the graph consists of disjoint cycles and  represents the number of ways we can color a cycle consisting of 
 nodes. The images are painted sequentially. The first image can be painted in 
 ways. The second can be painted in 
 ways because it has to differ from the first image. Analogously, it is concluded that in the 
 colorings, there will exist some colorings in which the image numbered 
 is of the same color as the image numbered 
. Connecting the nodes 
 and 
, if they're of the same color, a cycle sized 
 is created with differently colored nodes. We can conclude that the recursive relation applies: 
. Therefore, we can compute this function easily in linear complexity.
If the input numbers are not different, our cycles will have edges that are, in fact, trees. Let us imagine that we have colored the cycles and are now coloring those edges. The node connected directly with the cycle can be colored in  ways (it has to be different than the one connected to it), the node connected to it can be painted in also 
 ways and so on. It is a valid conclusion that for each node not belonging to the cycle, we have to multiply our current solution by 
.
We traverse the graph using DFS and decide how many cycles there are of different sizes.
Comments