Find out for each subset S of forbidden edges how many Hamiltonian cycles exist that use all edges of S. If we solve this subproblem, then we solve the inclusion exclusion exclusion formula problem.
Now, how do we solve the subtask? Let all edges of S be drawn. If there is a vertex of degree greater than 2, then obviously we cannot complete the cycle, and the answer is 0. Otherwise, the graph is divided into connected components. Each component is a single vertex, loop, or simple path.
If a cycle exists, then it must go through all the vertices, otherwise we will not be able to complete the Hamiltonian cycle. If so, the answer is 2. (The cycle can go in 2 directions.) Otherwise, the answer will be 0.
The case remains when there exist paths c and k are the only vertices. To complete the Hamilton cycle, we must choose the direction of each path ( 2 ^ c ), and then choose the order of the components. We have c + k components, so they can be rearranged in the path (c + k)! . But we are interested in cycles, so we do not distinguish between orderings that turn to each other by cyclic shifts. (So ​​(1,2,3), (2,3,1) and (3,1,2) are the same.) This means that we must divide the answer by the number of shifts, c + k . So the answer (to the subtask) is 2 ^ c (c + k-1)! .
This idea is implemented in the bmerry solution (very clean code, by the way).
source share